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