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