]> git.lizzy.rs Git - rust.git/blob - src/liballoc/string.rs
Remove unchecked inline attribute, remove unused functions, make chache mod private...
[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, with a required alignment of exactly 1.
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, not [`char`]s or
1406     /// graphemes. In other words, it may not be what a human considers the
1407     /// length of the string.
1408     ///
1409     /// # Examples
1410     ///
1411     /// Basic usage:
1412     ///
1413     /// ```
1414     /// let a = String::from("foo");
1415     /// assert_eq!(a.len(), 3);
1416     ///
1417     /// let fancy_f = String::from("ƒoo");
1418     /// assert_eq!(fancy_f.len(), 4);
1419     /// assert_eq!(fancy_f.chars().count(), 3);
1420     /// ```
1421     #[inline]
1422     #[stable(feature = "rust1", since = "1.0.0")]
1423     pub fn len(&self) -> usize {
1424         self.vec.len()
1425     }
1426
1427     /// Returns `true` if this `String` has a length of zero, and `false` otherwise.
1428     ///
1429     /// # Examples
1430     ///
1431     /// Basic usage:
1432     ///
1433     /// ```
1434     /// let mut v = String::new();
1435     /// assert!(v.is_empty());
1436     ///
1437     /// v.push('a');
1438     /// assert!(!v.is_empty());
1439     /// ```
1440     #[inline]
1441     #[stable(feature = "rust1", since = "1.0.0")]
1442     pub fn is_empty(&self) -> bool {
1443         self.len() == 0
1444     }
1445
1446     /// Splits the string into two at the given index.
1447     ///
1448     /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1449     /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1450     /// boundary of a UTF-8 code point.
1451     ///
1452     /// Note that the capacity of `self` does not change.
1453     ///
1454     /// # Panics
1455     ///
1456     /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1457     /// code point of the string.
1458     ///
1459     /// # Examples
1460     ///
1461     /// ```
1462     /// # fn main() {
1463     /// let mut hello = String::from("Hello, World!");
1464     /// let world = hello.split_off(7);
1465     /// assert_eq!(hello, "Hello, ");
1466     /// assert_eq!(world, "World!");
1467     /// # }
1468     /// ```
1469     #[inline]
1470     #[stable(feature = "string_split_off", since = "1.16.0")]
1471     pub fn split_off(&mut self, at: usize) -> String {
1472         assert!(self.is_char_boundary(at));
1473         let other = self.vec.split_off(at);
1474         unsafe { String::from_utf8_unchecked(other) }
1475     }
1476
1477     /// Truncates this `String`, removing all contents.
1478     ///
1479     /// While this means the `String` will have a length of zero, it does not
1480     /// touch its capacity.
1481     ///
1482     /// # Examples
1483     ///
1484     /// Basic usage:
1485     ///
1486     /// ```
1487     /// let mut s = String::from("foo");
1488     ///
1489     /// s.clear();
1490     ///
1491     /// assert!(s.is_empty());
1492     /// assert_eq!(0, s.len());
1493     /// assert_eq!(3, s.capacity());
1494     /// ```
1495     #[inline]
1496     #[stable(feature = "rust1", since = "1.0.0")]
1497     pub fn clear(&mut self) {
1498         self.vec.clear()
1499     }
1500
1501     /// Creates a draining iterator that removes the specified range in the `String`
1502     /// and yields the removed `chars`.
1503     ///
1504     /// Note: The element range is removed even if the iterator is not
1505     /// consumed until the end.
1506     ///
1507     /// # Panics
1508     ///
1509     /// Panics if the starting point or end point do not lie on a [`char`]
1510     /// boundary, or if they're out of bounds.
1511     ///
1512     /// [`char`]: ../../std/primitive.char.html
1513     ///
1514     /// # Examples
1515     ///
1516     /// Basic usage:
1517     ///
1518     /// ```
1519     /// let mut s = String::from("α is alpha, β is beta");
1520     /// let beta_offset = s.find('β').unwrap_or(s.len());
1521     ///
1522     /// // Remove the range up until the β from the string
1523     /// let t: String = s.drain(..beta_offset).collect();
1524     /// assert_eq!(t, "α is alpha, ");
1525     /// assert_eq!(s, "β is beta");
1526     ///
1527     /// // A full range clears the string
1528     /// s.drain(..);
1529     /// assert_eq!(s, "");
1530     /// ```
1531     #[stable(feature = "drain", since = "1.6.0")]
1532     pub fn drain<R>(&mut self, range: R) -> Drain<'_>
1533         where R: RangeBounds<usize>
1534     {
1535         // Memory safety
1536         //
1537         // The String version of Drain does not have the memory safety issues
1538         // of the vector version. The data is just plain bytes.
1539         // Because the range removal happens in Drop, if the Drain iterator is leaked,
1540         // the removal will not happen.
1541         let len = self.len();
1542         let start = match range.start_bound() {
1543             Included(&n) => n,
1544             Excluded(&n) => n + 1,
1545             Unbounded => 0,
1546         };
1547         let end = match range.end_bound() {
1548             Included(&n) => n + 1,
1549             Excluded(&n) => n,
1550             Unbounded => len,
1551         };
1552
1553         // Take out two simultaneous borrows. The &mut String won't be accessed
1554         // until iteration is over, in Drop.
1555         let self_ptr = self as *mut _;
1556         // slicing does the appropriate bounds checks
1557         let chars_iter = self[start..end].chars();
1558
1559         Drain {
1560             start,
1561             end,
1562             iter: chars_iter,
1563             string: self_ptr,
1564         }
1565     }
1566
1567     /// Removes the specified range in the string,
1568     /// and replaces it with the given string.
1569     /// The given string doesn't need to be the same length as the range.
1570     ///
1571     /// # Panics
1572     ///
1573     /// Panics if the starting point or end point do not lie on a [`char`]
1574     /// boundary, or if they're out of bounds.
1575     ///
1576     /// [`char`]: ../../std/primitive.char.html
1577     /// [`Vec::splice`]: ../../std/vec/struct.Vec.html#method.splice
1578     ///
1579     /// # Examples
1580     ///
1581     /// Basic usage:
1582     ///
1583     /// ```
1584     /// let mut s = String::from("α is alpha, β is beta");
1585     /// let beta_offset = s.find('β').unwrap_or(s.len());
1586     ///
1587     /// // Replace the range up until the β from the string
1588     /// s.replace_range(..beta_offset, "Α is capital alpha; ");
1589     /// assert_eq!(s, "Α is capital alpha; β is beta");
1590     /// ```
1591     #[stable(feature = "splice", since = "1.27.0")]
1592     pub fn replace_range<R>(&mut self, range: R, replace_with: &str)
1593         where R: RangeBounds<usize>
1594     {
1595         // Memory safety
1596         //
1597         // Replace_range does not have the memory safety issues of a vector Splice.
1598         // of the vector version. The data is just plain bytes.
1599
1600         match range.start_bound() {
1601              Included(&n) => assert!(self.is_char_boundary(n)),
1602              Excluded(&n) => assert!(self.is_char_boundary(n + 1)),
1603              Unbounded => {},
1604         };
1605         match range.end_bound() {
1606              Included(&n) => assert!(self.is_char_boundary(n + 1)),
1607              Excluded(&n) => assert!(self.is_char_boundary(n)),
1608              Unbounded => {},
1609         };
1610
1611         unsafe {
1612             self.as_mut_vec()
1613         }.splice(range, replace_with.bytes());
1614     }
1615
1616     /// Converts this `String` into a [`Box`]`<`[`str`]`>`.
1617     ///
1618     /// This will drop any excess capacity.
1619     ///
1620     /// [`Box`]: ../../std/boxed/struct.Box.html
1621     /// [`str`]: ../../std/primitive.str.html
1622     ///
1623     /// # Examples
1624     ///
1625     /// Basic usage:
1626     ///
1627     /// ```
1628     /// let s = String::from("hello");
1629     ///
1630     /// let b = s.into_boxed_str();
1631     /// ```
1632     #[stable(feature = "box_str", since = "1.4.0")]
1633     #[inline]
1634     pub fn into_boxed_str(self) -> Box<str> {
1635         let slice = self.vec.into_boxed_slice();
1636         unsafe { from_boxed_utf8_unchecked(slice) }
1637     }
1638 }
1639
1640 impl FromUtf8Error {
1641     /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
1642     ///
1643     /// # Examples
1644     ///
1645     /// Basic usage:
1646     ///
1647     /// ```
1648     /// // some invalid bytes, in a vector
1649     /// let bytes = vec![0, 159];
1650     ///
1651     /// let value = String::from_utf8(bytes);
1652     ///
1653     /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1654     /// ```
1655     #[stable(feature = "from_utf8_error_as_bytes", since = "1.26.0")]
1656     pub fn as_bytes(&self) -> &[u8] {
1657         &self.bytes[..]
1658     }
1659
1660     /// Returns the bytes that were attempted to convert to a `String`.
1661     ///
1662     /// This method is carefully constructed to avoid allocation. It will
1663     /// consume the error, moving out the bytes, so that a copy of the bytes
1664     /// does not need to be made.
1665     ///
1666     /// # Examples
1667     ///
1668     /// Basic usage:
1669     ///
1670     /// ```
1671     /// // some invalid bytes, in a vector
1672     /// let bytes = vec![0, 159];
1673     ///
1674     /// let value = String::from_utf8(bytes);
1675     ///
1676     /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1677     /// ```
1678     #[stable(feature = "rust1", since = "1.0.0")]
1679     pub fn into_bytes(self) -> Vec<u8> {
1680         self.bytes
1681     }
1682
1683     /// Fetch a `Utf8Error` to get more details about the conversion failure.
1684     ///
1685     /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1686     /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1687     /// an analogue to `FromUtf8Error`. See its documentation for more details
1688     /// on using it.
1689     ///
1690     /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
1691     /// [`std::str`]: ../../std/str/index.html
1692     /// [`u8`]: ../../std/primitive.u8.html
1693     /// [`&str`]: ../../std/primitive.str.html
1694     ///
1695     /// # Examples
1696     ///
1697     /// Basic usage:
1698     ///
1699     /// ```
1700     /// // some invalid bytes, in a vector
1701     /// let bytes = vec![0, 159];
1702     ///
1703     /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1704     ///
1705     /// // the first byte is invalid here
1706     /// assert_eq!(1, error.valid_up_to());
1707     /// ```
1708     #[stable(feature = "rust1", since = "1.0.0")]
1709     pub fn utf8_error(&self) -> Utf8Error {
1710         self.error
1711     }
1712 }
1713
1714 #[stable(feature = "rust1", since = "1.0.0")]
1715 impl fmt::Display for FromUtf8Error {
1716     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1717         fmt::Display::fmt(&self.error, f)
1718     }
1719 }
1720
1721 #[stable(feature = "rust1", since = "1.0.0")]
1722 impl fmt::Display for FromUtf16Error {
1723     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1724         fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1725     }
1726 }
1727
1728 #[stable(feature = "rust1", since = "1.0.0")]
1729 impl Clone for String {
1730     fn clone(&self) -> Self {
1731         String { vec: self.vec.clone() }
1732     }
1733
1734     fn clone_from(&mut self, source: &Self) {
1735         self.vec.clone_from(&source.vec);
1736     }
1737 }
1738
1739 #[stable(feature = "rust1", since = "1.0.0")]
1740 impl FromIterator<char> for String {
1741     fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1742         let mut buf = String::new();
1743         buf.extend(iter);
1744         buf
1745     }
1746 }
1747
1748 #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
1749 impl<'a> FromIterator<&'a char> for String {
1750     fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
1751         let mut buf = String::new();
1752         buf.extend(iter);
1753         buf
1754     }
1755 }
1756
1757 #[stable(feature = "rust1", since = "1.0.0")]
1758 impl<'a> FromIterator<&'a str> for String {
1759     fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1760         let mut buf = String::new();
1761         buf.extend(iter);
1762         buf
1763     }
1764 }
1765
1766 #[stable(feature = "extend_string", since = "1.4.0")]
1767 impl FromIterator<String> for String {
1768     fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1769         let mut iterator = iter.into_iter();
1770
1771         // Because we're iterating over `String`s, we can avoid at least
1772         // one allocation by getting the first string from the iterator
1773         // and appending to it all the subsequent strings.
1774         match iterator.next() {
1775             None => String::new(),
1776             Some(mut buf) => {
1777                 buf.extend(iterator);
1778                 buf
1779             }
1780         }
1781     }
1782 }
1783
1784 #[stable(feature = "herd_cows", since = "1.19.0")]
1785 impl<'a> FromIterator<Cow<'a, str>> for String {
1786     fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> String {
1787         let mut iterator = iter.into_iter();
1788
1789         // Because we're iterating over CoWs, we can (potentially) avoid at least
1790         // one allocation by getting the first item and appending to it all the
1791         // subsequent items.
1792         match iterator.next() {
1793             None => String::new(),
1794             Some(cow) => {
1795                 let mut buf = cow.into_owned();
1796                 buf.extend(iterator);
1797                 buf
1798             }
1799         }
1800     }
1801 }
1802
1803 #[stable(feature = "rust1", since = "1.0.0")]
1804 impl Extend<char> for String {
1805     fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1806         let iterator = iter.into_iter();
1807         let (lower_bound, _) = iterator.size_hint();
1808         self.reserve(lower_bound);
1809         iterator.for_each(move |c| self.push(c));
1810     }
1811 }
1812
1813 #[stable(feature = "extend_ref", since = "1.2.0")]
1814 impl<'a> Extend<&'a char> for String {
1815     fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1816         self.extend(iter.into_iter().cloned());
1817     }
1818 }
1819
1820 #[stable(feature = "rust1", since = "1.0.0")]
1821 impl<'a> Extend<&'a str> for String {
1822     fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1823         iter.into_iter().for_each(move |s| self.push_str(s));
1824     }
1825 }
1826
1827 #[stable(feature = "extend_string", since = "1.4.0")]
1828 impl Extend<String> for String {
1829     fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1830         iter.into_iter().for_each(move |s| self.push_str(&s));
1831     }
1832 }
1833
1834 #[stable(feature = "herd_cows", since = "1.19.0")]
1835 impl<'a> Extend<Cow<'a, str>> for String {
1836     fn extend<I: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: I) {
1837         iter.into_iter().for_each(move |s| self.push_str(&s));
1838     }
1839 }
1840
1841 /// A convenience impl that delegates to the impl for `&str`
1842 #[unstable(feature = "pattern",
1843            reason = "API not fully fleshed out and ready to be stabilized",
1844            issue = "27721")]
1845 impl<'a, 'b> Pattern<'a> for &'b String {
1846     type Searcher = <&'b str as Pattern<'a>>::Searcher;
1847
1848     fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1849         self[..].into_searcher(haystack)
1850     }
1851
1852     #[inline]
1853     fn is_contained_in(self, haystack: &'a str) -> bool {
1854         self[..].is_contained_in(haystack)
1855     }
1856
1857     #[inline]
1858     fn is_prefix_of(self, haystack: &'a str) -> bool {
1859         self[..].is_prefix_of(haystack)
1860     }
1861 }
1862
1863 #[stable(feature = "rust1", since = "1.0.0")]
1864 impl PartialEq for String {
1865     #[inline]
1866     fn eq(&self, other: &String) -> bool {
1867         PartialEq::eq(&self[..], &other[..])
1868     }
1869     #[inline]
1870     fn ne(&self, other: &String) -> bool {
1871         PartialEq::ne(&self[..], &other[..])
1872     }
1873 }
1874
1875 macro_rules! impl_eq {
1876     ($lhs:ty, $rhs: ty) => {
1877         #[stable(feature = "rust1", since = "1.0.0")]
1878         #[allow(unused_lifetimes)]
1879         impl<'a, 'b> PartialEq<$rhs> for $lhs {
1880             #[inline]
1881             fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1882             #[inline]
1883             fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1884         }
1885
1886         #[stable(feature = "rust1", since = "1.0.0")]
1887         #[allow(unused_lifetimes)]
1888         impl<'a, 'b> PartialEq<$lhs> for $rhs {
1889             #[inline]
1890             fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1891             #[inline]
1892             fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1893         }
1894
1895     }
1896 }
1897
1898 impl_eq! { String, str }
1899 impl_eq! { String, &'a str }
1900 impl_eq! { Cow<'a, str>, str }
1901 impl_eq! { Cow<'a, str>, &'b str }
1902 impl_eq! { Cow<'a, str>, String }
1903
1904 #[stable(feature = "rust1", since = "1.0.0")]
1905 impl Default for String {
1906     /// Creates an empty `String`.
1907     #[inline]
1908     fn default() -> String {
1909         String::new()
1910     }
1911 }
1912
1913 #[stable(feature = "rust1", since = "1.0.0")]
1914 impl fmt::Display for String {
1915     #[inline]
1916     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1917         fmt::Display::fmt(&**self, f)
1918     }
1919 }
1920
1921 #[stable(feature = "rust1", since = "1.0.0")]
1922 impl fmt::Debug for String {
1923     #[inline]
1924     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1925         fmt::Debug::fmt(&**self, f)
1926     }
1927 }
1928
1929 #[stable(feature = "rust1", since = "1.0.0")]
1930 impl hash::Hash for String {
1931     #[inline]
1932     fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1933         (**self).hash(hasher)
1934     }
1935 }
1936
1937 /// Implements the `+` operator for concatenating two strings.
1938 ///
1939 /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
1940 /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
1941 /// every operation, which would lead to `O(n^2)` running time when building an `n`-byte string by
1942 /// repeated concatenation.
1943 ///
1944 /// The string on the right-hand side is only borrowed; its contents are copied into the returned
1945 /// `String`.
1946 ///
1947 /// # Examples
1948 ///
1949 /// Concatenating two `String`s takes the first by value and borrows the second:
1950 ///
1951 /// ```
1952 /// let a = String::from("hello");
1953 /// let b = String::from(" world");
1954 /// let c = a + &b;
1955 /// // `a` is moved and can no longer be used here.
1956 /// ```
1957 ///
1958 /// If you want to keep using the first `String`, you can clone it and append to the clone instead:
1959 ///
1960 /// ```
1961 /// let a = String::from("hello");
1962 /// let b = String::from(" world");
1963 /// let c = a.clone() + &b;
1964 /// // `a` is still valid here.
1965 /// ```
1966 ///
1967 /// Concatenating `&str` slices can be done by converting the first to a `String`:
1968 ///
1969 /// ```
1970 /// let a = "hello";
1971 /// let b = " world";
1972 /// let c = a.to_string() + b;
1973 /// ```
1974 #[stable(feature = "rust1", since = "1.0.0")]
1975 impl Add<&str> for String {
1976     type Output = String;
1977
1978     #[inline]
1979     fn add(mut self, other: &str) -> String {
1980         self.push_str(other);
1981         self
1982     }
1983 }
1984
1985 /// Implements the `+=` operator for appending to a `String`.
1986 ///
1987 /// This has the same behavior as the [`push_str`][String::push_str] method.
1988 #[stable(feature = "stringaddassign", since = "1.12.0")]
1989 impl AddAssign<&str> for String {
1990     #[inline]
1991     fn add_assign(&mut self, other: &str) {
1992         self.push_str(other);
1993     }
1994 }
1995
1996 #[stable(feature = "rust1", since = "1.0.0")]
1997 impl ops::Index<ops::Range<usize>> for String {
1998     type Output = str;
1999
2000     #[inline]
2001     fn index(&self, index: ops::Range<usize>) -> &str {
2002         &self[..][index]
2003     }
2004 }
2005 #[stable(feature = "rust1", since = "1.0.0")]
2006 impl ops::Index<ops::RangeTo<usize>> for String {
2007     type Output = str;
2008
2009     #[inline]
2010     fn index(&self, index: ops::RangeTo<usize>) -> &str {
2011         &self[..][index]
2012     }
2013 }
2014 #[stable(feature = "rust1", since = "1.0.0")]
2015 impl ops::Index<ops::RangeFrom<usize>> for String {
2016     type Output = str;
2017
2018     #[inline]
2019     fn index(&self, index: ops::RangeFrom<usize>) -> &str {
2020         &self[..][index]
2021     }
2022 }
2023 #[stable(feature = "rust1", since = "1.0.0")]
2024 impl ops::Index<ops::RangeFull> for String {
2025     type Output = str;
2026
2027     #[inline]
2028     fn index(&self, _index: ops::RangeFull) -> &str {
2029         unsafe { str::from_utf8_unchecked(&self.vec) }
2030     }
2031 }
2032 #[stable(feature = "inclusive_range", since = "1.26.0")]
2033 impl ops::Index<ops::RangeInclusive<usize>> for String {
2034     type Output = str;
2035
2036     #[inline]
2037     fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
2038         Index::index(&**self, index)
2039     }
2040 }
2041 #[stable(feature = "inclusive_range", since = "1.26.0")]
2042 impl ops::Index<ops::RangeToInclusive<usize>> for String {
2043     type Output = str;
2044
2045     #[inline]
2046     fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
2047         Index::index(&**self, index)
2048     }
2049 }
2050
2051 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2052 impl ops::IndexMut<ops::Range<usize>> for String {
2053     #[inline]
2054     fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
2055         &mut self[..][index]
2056     }
2057 }
2058 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2059 impl ops::IndexMut<ops::RangeTo<usize>> for String {
2060     #[inline]
2061     fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
2062         &mut self[..][index]
2063     }
2064 }
2065 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2066 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
2067     #[inline]
2068     fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
2069         &mut self[..][index]
2070     }
2071 }
2072 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2073 impl ops::IndexMut<ops::RangeFull> for String {
2074     #[inline]
2075     fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
2076         unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2077     }
2078 }
2079 #[stable(feature = "inclusive_range", since = "1.26.0")]
2080 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
2081     #[inline]
2082     fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
2083         IndexMut::index_mut(&mut **self, index)
2084     }
2085 }
2086 #[stable(feature = "inclusive_range", since = "1.26.0")]
2087 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
2088     #[inline]
2089     fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
2090         IndexMut::index_mut(&mut **self, index)
2091     }
2092 }
2093
2094 #[stable(feature = "rust1", since = "1.0.0")]
2095 impl ops::Deref for String {
2096     type Target = str;
2097
2098     #[inline]
2099     fn deref(&self) -> &str {
2100         unsafe { str::from_utf8_unchecked(&self.vec) }
2101     }
2102 }
2103
2104 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2105 impl ops::DerefMut for String {
2106     #[inline]
2107     fn deref_mut(&mut self) -> &mut str {
2108         unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2109     }
2110 }
2111
2112 /// An error when parsing a `String`.
2113 ///
2114 /// This `enum` is slightly awkward: it will never actually exist. This error is
2115 /// part of the type signature of the implementation of [`FromStr`] on
2116 /// [`String`]. The return type of [`from_str`], requires that an error be
2117 /// defined, but, given that a [`String`] can always be made into a new
2118 /// [`String`] without error, this type will never actually be returned. As
2119 /// such, it is only here to satisfy said signature, and is useless otherwise.
2120 ///
2121 /// [`FromStr`]: ../../std/str/trait.FromStr.html
2122 /// [`String`]: struct.String.html
2123 /// [`from_str`]: ../../std/str/trait.FromStr.html#tymethod.from_str
2124 #[stable(feature = "str_parse_error", since = "1.5.0")]
2125 pub type ParseError = core::convert::Infallible;
2126
2127 #[stable(feature = "rust1", since = "1.0.0")]
2128 impl FromStr for String {
2129     type Err = core::convert::Infallible;
2130     #[inline]
2131     fn from_str(s: &str) -> Result<String, ParseError> {
2132         Ok(String::from(s))
2133     }
2134 }
2135
2136
2137 /// A trait for converting a value to a `String`.
2138 ///
2139 /// This trait is automatically implemented for any type which implements the
2140 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
2141 /// [`Display`] should be implemented instead, and you get the `ToString`
2142 /// implementation for free.
2143 ///
2144 /// [`Display`]: ../../std/fmt/trait.Display.html
2145 #[stable(feature = "rust1", since = "1.0.0")]
2146 pub trait ToString {
2147     /// Converts the given value to a `String`.
2148     ///
2149     /// # Examples
2150     ///
2151     /// Basic usage:
2152     ///
2153     /// ```
2154     /// let i = 5;
2155     /// let five = String::from("5");
2156     ///
2157     /// assert_eq!(five, i.to_string());
2158     /// ```
2159     #[rustc_conversion_suggestion]
2160     #[stable(feature = "rust1", since = "1.0.0")]
2161     fn to_string(&self) -> String;
2162 }
2163
2164 /// # Panics
2165 ///
2166 /// In this implementation, the `to_string` method panics
2167 /// if the `Display` implementation returns an error.
2168 /// This indicates an incorrect `Display` implementation
2169 /// since `fmt::Write for String` never returns an error itself.
2170 #[stable(feature = "rust1", since = "1.0.0")]
2171 impl<T: fmt::Display + ?Sized> ToString for T {
2172     #[inline]
2173     default fn to_string(&self) -> String {
2174         use fmt::Write;
2175         let mut buf = String::new();
2176         buf.write_fmt(format_args!("{}", self))
2177            .expect("a Display implementation returned an error unexpectedly");
2178         buf.shrink_to_fit();
2179         buf
2180     }
2181 }
2182
2183 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
2184 impl ToString for str {
2185     #[inline]
2186     fn to_string(&self) -> String {
2187         String::from(self)
2188     }
2189 }
2190
2191 #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")]
2192 impl ToString for Cow<'_, str> {
2193     #[inline]
2194     fn to_string(&self) -> String {
2195         self[..].to_owned()
2196     }
2197 }
2198
2199 #[stable(feature = "string_to_string_specialization", since = "1.17.0")]
2200 impl ToString for String {
2201     #[inline]
2202     fn to_string(&self) -> String {
2203         self.to_owned()
2204     }
2205 }
2206
2207 #[stable(feature = "rust1", since = "1.0.0")]
2208 impl AsRef<str> for String {
2209     #[inline]
2210     fn as_ref(&self) -> &str {
2211         self
2212     }
2213 }
2214
2215 #[stable(feature = "rust1", since = "1.0.0")]
2216 impl AsRef<[u8]> for String {
2217     #[inline]
2218     fn as_ref(&self) -> &[u8] {
2219         self.as_bytes()
2220     }
2221 }
2222
2223 #[stable(feature = "rust1", since = "1.0.0")]
2224 impl From<&str> for String {
2225     #[inline]
2226     fn from(s: &str) -> String {
2227         s.to_owned()
2228     }
2229 }
2230
2231 #[stable(feature = "from_ref_string", since = "1.35.0")]
2232 impl From<&String> for String {
2233     #[inline]
2234     fn from(s: &String) -> String {
2235         s.clone()
2236     }
2237 }
2238
2239 // note: test pulls in libstd, which causes errors here
2240 #[cfg(not(test))]
2241 #[stable(feature = "string_from_box", since = "1.18.0")]
2242 impl From<Box<str>> for String {
2243     /// Converts the given boxed `str` slice to a `String`.
2244     /// It is notable that the `str` slice is owned.
2245     ///
2246     /// # Examples
2247     ///
2248     /// Basic usage:
2249     ///
2250     /// ```
2251     /// let s1: String = String::from("hello world");
2252     /// let s2: Box<str> = s1.into_boxed_str();
2253     /// let s3: String = String::from(s2);
2254     ///
2255     /// assert_eq!("hello world", s3)
2256     /// ```
2257     fn from(s: Box<str>) -> String {
2258         s.into_string()
2259     }
2260 }
2261
2262 #[stable(feature = "box_from_str", since = "1.20.0")]
2263 impl From<String> for Box<str> {
2264     /// Converts the given `String` to a boxed `str` slice that is owned.
2265     ///
2266     /// # Examples
2267     ///
2268     /// Basic usage:
2269     ///
2270     /// ```
2271     /// let s1: String = String::from("hello world");
2272     /// let s2: Box<str> = Box::from(s1);
2273     /// let s3: String = String::from(s2);
2274     ///
2275     /// assert_eq!("hello world", s3)
2276     /// ```
2277     fn from(s: String) -> Box<str> {
2278         s.into_boxed_str()
2279     }
2280 }
2281
2282 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
2283 impl<'a> From<Cow<'a, str>> for String {
2284     fn from(s: Cow<'a, str>) -> String {
2285         s.into_owned()
2286     }
2287 }
2288
2289 #[stable(feature = "rust1", since = "1.0.0")]
2290 impl<'a> From<&'a str> for Cow<'a, str> {
2291     #[inline]
2292     fn from(s: &'a str) -> Cow<'a, str> {
2293         Cow::Borrowed(s)
2294     }
2295 }
2296
2297 #[stable(feature = "rust1", since = "1.0.0")]
2298 impl<'a> From<String> for Cow<'a, str> {
2299     #[inline]
2300     fn from(s: String) -> Cow<'a, str> {
2301         Cow::Owned(s)
2302     }
2303 }
2304
2305 #[stable(feature = "cow_from_string_ref", since = "1.28.0")]
2306 impl<'a> From<&'a String> for Cow<'a, str> {
2307     #[inline]
2308     fn from(s: &'a String) -> Cow<'a, str> {
2309         Cow::Borrowed(s.as_str())
2310     }
2311 }
2312
2313 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2314 impl<'a> FromIterator<char> for Cow<'a, str> {
2315     fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
2316         Cow::Owned(FromIterator::from_iter(it))
2317     }
2318 }
2319
2320 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2321 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
2322     fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
2323         Cow::Owned(FromIterator::from_iter(it))
2324     }
2325 }
2326
2327 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2328 impl<'a> FromIterator<String> for Cow<'a, str> {
2329     fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
2330         Cow::Owned(FromIterator::from_iter(it))
2331     }
2332 }
2333
2334 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
2335 impl From<String> for Vec<u8> {
2336     /// Converts the given `String` to a vector `Vec` that holds values of type `u8`.
2337     ///
2338     /// # Examples
2339     ///
2340     /// Basic usage:
2341     ///
2342     /// ```
2343     /// let s1 = String::from("hello world");
2344     /// let v1 = Vec::from(s1);
2345     ///
2346     /// for b in v1 {
2347     ///     println!("{}", b);
2348     /// }
2349     /// ```
2350     fn from(string: String) -> Vec<u8> {
2351         string.into_bytes()
2352     }
2353 }
2354
2355 #[stable(feature = "rust1", since = "1.0.0")]
2356 impl fmt::Write for String {
2357     #[inline]
2358     fn write_str(&mut self, s: &str) -> fmt::Result {
2359         self.push_str(s);
2360         Ok(())
2361     }
2362
2363     #[inline]
2364     fn write_char(&mut self, c: char) -> fmt::Result {
2365         self.push(c);
2366         Ok(())
2367     }
2368 }
2369
2370 /// A draining iterator for `String`.
2371 ///
2372 /// This struct is created by the [`drain`] method on [`String`]. See its
2373 /// documentation for more.
2374 ///
2375 /// [`drain`]: struct.String.html#method.drain
2376 /// [`String`]: struct.String.html
2377 #[stable(feature = "drain", since = "1.6.0")]
2378 pub struct Drain<'a> {
2379     /// Will be used as &'a mut String in the destructor
2380     string: *mut String,
2381     /// Start of part to remove
2382     start: usize,
2383     /// End of part to remove
2384     end: usize,
2385     /// Current remaining range to remove
2386     iter: Chars<'a>,
2387 }
2388
2389 #[stable(feature = "collection_debug", since = "1.17.0")]
2390 impl fmt::Debug for Drain<'_> {
2391     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2392         f.pad("Drain { .. }")
2393     }
2394 }
2395
2396 #[stable(feature = "drain", since = "1.6.0")]
2397 unsafe impl Sync for Drain<'_> {}
2398 #[stable(feature = "drain", since = "1.6.0")]
2399 unsafe impl Send for Drain<'_> {}
2400
2401 #[stable(feature = "drain", since = "1.6.0")]
2402 impl Drop for Drain<'_> {
2403     fn drop(&mut self) {
2404         unsafe {
2405             // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2406             // panic code being inserted again.
2407             let self_vec = (*self.string).as_mut_vec();
2408             if self.start <= self.end && self.end <= self_vec.len() {
2409                 self_vec.drain(self.start..self.end);
2410             }
2411         }
2412     }
2413 }
2414
2415 #[stable(feature = "drain", since = "1.6.0")]
2416 impl Iterator for Drain<'_> {
2417     type Item = char;
2418
2419     #[inline]
2420     fn next(&mut self) -> Option<char> {
2421         self.iter.next()
2422     }
2423
2424     fn size_hint(&self) -> (usize, Option<usize>) {
2425         self.iter.size_hint()
2426     }
2427
2428     #[inline]
2429     fn last(mut self) -> Option<char> {
2430         self.next_back()
2431     }
2432 }
2433
2434 #[stable(feature = "drain", since = "1.6.0")]
2435 impl DoubleEndedIterator for Drain<'_> {
2436     #[inline]
2437     fn next_back(&mut self) -> Option<char> {
2438         self.iter.next_back()
2439     }
2440 }
2441
2442 #[stable(feature = "fused", since = "1.26.0")]
2443 impl FusedIterator for Drain<'_> {}