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