]> git.lizzy.rs Git - rust.git/blob - src/liballoc/string.rs
Auto merge of #43903 - oli-obk:alignto, r=aturon
[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     /// # Examples
626     ///
627     /// Basic usage:
628     ///
629     /// ```
630     /// // 𝄞mus<invalid>ic<invalid>
631     /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
632     ///           0x0073, 0xDD1E, 0x0069, 0x0063,
633     ///           0xD834];
634     ///
635     /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
636     ///            String::from_utf16_lossy(v));
637     /// ```
638     #[inline]
639     #[stable(feature = "rust1", since = "1.0.0")]
640     pub fn from_utf16_lossy(v: &[u16]) -> String {
641         decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
642     }
643
644     /// Creates a new `String` from a length, capacity, and pointer.
645     ///
646     /// # Safety
647     ///
648     /// This is highly unsafe, due to the number of invariants that aren't
649     /// checked:
650     ///
651     /// * The memory at `ptr` needs to have been previously allocated by the
652     ///   same allocator the standard library uses.
653     /// * `length` needs to be less than or equal to `capacity`.
654     /// * `capacity` needs to be the correct value.
655     ///
656     /// Violating these may cause problems like corrupting the allocator's
657     /// internal data structures.
658     ///
659     /// The ownership of `ptr` is effectively transferred to the
660     /// `String` which may then deallocate, reallocate or change the
661     /// contents of memory pointed to by the pointer at will. Ensure
662     /// that nothing else uses the pointer after calling this
663     /// function.
664     ///
665     /// # Examples
666     ///
667     /// Basic usage:
668     ///
669     /// ```
670     /// use std::mem;
671     ///
672     /// unsafe {
673     ///     let s = String::from("hello");
674     ///     let ptr = s.as_ptr();
675     ///     let len = s.len();
676     ///     let capacity = s.capacity();
677     ///
678     ///     mem::forget(s);
679     ///
680     ///     let s = String::from_raw_parts(ptr as *mut _, len, capacity);
681     ///
682     ///     assert_eq!(String::from("hello"), s);
683     /// }
684     /// ```
685     #[inline]
686     #[stable(feature = "rust1", since = "1.0.0")]
687     pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
688         String { vec: Vec::from_raw_parts(buf, length, capacity) }
689     }
690
691     /// Converts a vector of bytes to a `String` without checking that the
692     /// string contains valid UTF-8.
693     ///
694     /// See the safe version, [`from_utf8`], for more details.
695     ///
696     /// [`from_utf8`]: struct.String.html#method.from_utf8
697     ///
698     /// # Safety
699     ///
700     /// This function is unsafe because it does not check that the bytes passed
701     /// to it are valid UTF-8. If this constraint is violated, it may cause
702     /// memory unsafety issues with future users of the `String`, as the rest of
703     /// the standard library assumes that `String`s are valid UTF-8.
704     ///
705     /// # Examples
706     ///
707     /// Basic usage:
708     ///
709     /// ```
710     /// // some bytes, in a vector
711     /// let sparkle_heart = vec![240, 159, 146, 150];
712     ///
713     /// let sparkle_heart = unsafe {
714     ///     String::from_utf8_unchecked(sparkle_heart)
715     /// };
716     ///
717     /// assert_eq!("💖", sparkle_heart);
718     /// ```
719     #[inline]
720     #[stable(feature = "rust1", since = "1.0.0")]
721     pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
722         String { vec: bytes }
723     }
724
725     /// Converts a `String` into a byte vector.
726     ///
727     /// This consumes the `String`, so we do not need to copy its contents.
728     ///
729     /// # Examples
730     ///
731     /// Basic usage:
732     ///
733     /// ```
734     /// let s = String::from("hello");
735     /// let bytes = s.into_bytes();
736     ///
737     /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
738     /// ```
739     #[inline]
740     #[stable(feature = "rust1", since = "1.0.0")]
741     pub fn into_bytes(self) -> Vec<u8> {
742         self.vec
743     }
744
745     /// Extracts a string slice containing the entire string.
746     #[inline]
747     #[stable(feature = "string_as_str", since = "1.7.0")]
748     pub fn as_str(&self) -> &str {
749         self
750     }
751
752     /// Extracts a string slice containing the entire string.
753     #[inline]
754     #[stable(feature = "string_as_str", since = "1.7.0")]
755     pub fn as_mut_str(&mut self) -> &mut str {
756         self
757     }
758
759     /// Appends a given string slice onto the end of this `String`.
760     ///
761     /// # Examples
762     ///
763     /// Basic usage:
764     ///
765     /// ```
766     /// let mut s = String::from("foo");
767     ///
768     /// s.push_str("bar");
769     ///
770     /// assert_eq!("foobar", s);
771     /// ```
772     #[inline]
773     #[stable(feature = "rust1", since = "1.0.0")]
774     pub fn push_str(&mut self, string: &str) {
775         self.vec.extend_from_slice(string.as_bytes())
776     }
777
778     /// Returns this `String`'s capacity, in bytes.
779     ///
780     /// # Examples
781     ///
782     /// Basic usage:
783     ///
784     /// ```
785     /// let s = String::with_capacity(10);
786     ///
787     /// assert!(s.capacity() >= 10);
788     /// ```
789     #[inline]
790     #[stable(feature = "rust1", since = "1.0.0")]
791     pub fn capacity(&self) -> usize {
792         self.vec.capacity()
793     }
794
795     /// Ensures that this `String`'s capacity is at least `additional` bytes
796     /// larger than its length.
797     ///
798     /// The capacity may be increased by more than `additional` bytes if it
799     /// chooses, to prevent frequent reallocations.
800     ///
801     /// If you do not want this "at least" behavior, see the [`reserve_exact`]
802     /// method.
803     ///
804     /// # Panics
805     ///
806     /// Panics if the new capacity overflows [`usize`].
807     ///
808     /// [`reserve_exact`]: struct.String.html#method.reserve_exact
809     /// [`usize`]: ../../std/primitive.usize.html
810     ///
811     /// # Examples
812     ///
813     /// Basic usage:
814     ///
815     /// ```
816     /// let mut s = String::new();
817     ///
818     /// s.reserve(10);
819     ///
820     /// assert!(s.capacity() >= 10);
821     /// ```
822     ///
823     /// This may not actually increase the capacity:
824     ///
825     /// ```
826     /// let mut s = String::with_capacity(10);
827     /// s.push('a');
828     /// s.push('b');
829     ///
830     /// // s now has a length of 2 and a capacity of 10
831     /// assert_eq!(2, s.len());
832     /// assert_eq!(10, s.capacity());
833     ///
834     /// // Since we already have an extra 8 capacity, calling this...
835     /// s.reserve(8);
836     ///
837     /// // ... doesn't actually increase.
838     /// assert_eq!(10, s.capacity());
839     /// ```
840     #[inline]
841     #[stable(feature = "rust1", since = "1.0.0")]
842     pub fn reserve(&mut self, additional: usize) {
843         self.vec.reserve(additional)
844     }
845
846     /// Ensures that this `String`'s capacity is `additional` bytes
847     /// larger than its length.
848     ///
849     /// Consider using the [`reserve`] method unless you absolutely know
850     /// better than the allocator.
851     ///
852     /// [`reserve`]: #method.reserve
853     ///
854     /// # Panics
855     ///
856     /// Panics if the new capacity overflows `usize`.
857     ///
858     /// # Examples
859     ///
860     /// Basic usage:
861     ///
862     /// ```
863     /// let mut s = String::new();
864     ///
865     /// s.reserve_exact(10);
866     ///
867     /// assert!(s.capacity() >= 10);
868     /// ```
869     ///
870     /// This may not actually increase the capacity:
871     ///
872     /// ```
873     /// let mut s = String::with_capacity(10);
874     /// s.push('a');
875     /// s.push('b');
876     ///
877     /// // s now has a length of 2 and a capacity of 10
878     /// assert_eq!(2, s.len());
879     /// assert_eq!(10, s.capacity());
880     ///
881     /// // Since we already have an extra 8 capacity, calling this...
882     /// s.reserve_exact(8);
883     ///
884     /// // ... doesn't actually increase.
885     /// assert_eq!(10, s.capacity());
886     /// ```
887     #[inline]
888     #[stable(feature = "rust1", since = "1.0.0")]
889     pub fn reserve_exact(&mut self, additional: usize) {
890         self.vec.reserve_exact(additional)
891     }
892
893     /// Shrinks the capacity of this `String` to match its length.
894     ///
895     /// # Examples
896     ///
897     /// Basic usage:
898     ///
899     /// ```
900     /// let mut s = String::from("foo");
901     ///
902     /// s.reserve(100);
903     /// assert!(s.capacity() >= 100);
904     ///
905     /// s.shrink_to_fit();
906     /// assert_eq!(3, s.capacity());
907     /// ```
908     #[inline]
909     #[stable(feature = "rust1", since = "1.0.0")]
910     pub fn shrink_to_fit(&mut self) {
911         self.vec.shrink_to_fit()
912     }
913
914     /// Appends the given [`char`] to the end of this `String`.
915     ///
916     /// [`char`]: ../../std/primitive.char.html
917     ///
918     /// # Examples
919     ///
920     /// Basic usage:
921     ///
922     /// ```
923     /// let mut s = String::from("abc");
924     ///
925     /// s.push('1');
926     /// s.push('2');
927     /// s.push('3');
928     ///
929     /// assert_eq!("abc123", s);
930     /// ```
931     #[inline]
932     #[stable(feature = "rust1", since = "1.0.0")]
933     pub fn push(&mut self, ch: char) {
934         match ch.len_utf8() {
935             1 => self.vec.push(ch as u8),
936             _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
937         }
938     }
939
940     /// Returns a byte slice of this `String`'s contents.
941     ///
942     /// The inverse of this method is [`from_utf8`].
943     ///
944     /// [`from_utf8`]: #method.from_utf8
945     ///
946     /// # Examples
947     ///
948     /// Basic usage:
949     ///
950     /// ```
951     /// let s = String::from("hello");
952     ///
953     /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
954     /// ```
955     #[inline]
956     #[stable(feature = "rust1", since = "1.0.0")]
957     pub fn as_bytes(&self) -> &[u8] {
958         &self.vec
959     }
960
961     /// Shortens this `String` to the specified length.
962     ///
963     /// If `new_len` is greater than the string's current length, this has no
964     /// effect.
965     ///
966     /// Note that this method has no effect on the allocated capacity
967     /// of the string
968     ///
969     /// # Panics
970     ///
971     /// Panics if `new_len` does not lie on a [`char`] boundary.
972     ///
973     /// [`char`]: ../../std/primitive.char.html
974     ///
975     /// # Examples
976     ///
977     /// Basic usage:
978     ///
979     /// ```
980     /// let mut s = String::from("hello");
981     ///
982     /// s.truncate(2);
983     ///
984     /// assert_eq!("he", s);
985     /// ```
986     #[inline]
987     #[stable(feature = "rust1", since = "1.0.0")]
988     pub fn truncate(&mut self, new_len: usize) {
989         if new_len <= self.len() {
990             assert!(self.is_char_boundary(new_len));
991             self.vec.truncate(new_len)
992         }
993     }
994
995     /// Removes the last character from the string buffer and returns it.
996     ///
997     /// Returns [`None`] if this `String` is empty.
998     ///
999     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1000     ///
1001     /// # Examples
1002     ///
1003     /// Basic usage:
1004     ///
1005     /// ```
1006     /// let mut s = String::from("foo");
1007     ///
1008     /// assert_eq!(s.pop(), Some('o'));
1009     /// assert_eq!(s.pop(), Some('o'));
1010     /// assert_eq!(s.pop(), Some('f'));
1011     ///
1012     /// assert_eq!(s.pop(), None);
1013     /// ```
1014     #[inline]
1015     #[stable(feature = "rust1", since = "1.0.0")]
1016     pub fn pop(&mut self) -> Option<char> {
1017         let ch = match self.chars().rev().next() {
1018             Some(ch) => ch,
1019             None => return None,
1020         };
1021         let newlen = self.len() - ch.len_utf8();
1022         unsafe {
1023             self.vec.set_len(newlen);
1024         }
1025         Some(ch)
1026     }
1027
1028     /// Removes a [`char`] from this `String` at a byte position and returns it.
1029     ///
1030     /// This is an `O(n)` operation, as it requires copying every element in the
1031     /// buffer.
1032     ///
1033     /// # Panics
1034     ///
1035     /// Panics if `idx` is larger than or equal to the `String`'s length,
1036     /// or if it does not lie on a [`char`] boundary.
1037     ///
1038     /// [`char`]: ../../std/primitive.char.html
1039     ///
1040     /// # Examples
1041     ///
1042     /// Basic usage:
1043     ///
1044     /// ```
1045     /// let mut s = String::from("foo");
1046     ///
1047     /// assert_eq!(s.remove(0), 'f');
1048     /// assert_eq!(s.remove(1), 'o');
1049     /// assert_eq!(s.remove(0), 'o');
1050     /// ```
1051     #[inline]
1052     #[stable(feature = "rust1", since = "1.0.0")]
1053     pub fn remove(&mut self, idx: usize) -> char {
1054         let ch = match self[idx..].chars().next() {
1055             Some(ch) => ch,
1056             None => panic!("cannot remove a char from the end of a string"),
1057         };
1058
1059         let next = idx + ch.len_utf8();
1060         let len = self.len();
1061         unsafe {
1062             ptr::copy(self.vec.as_ptr().offset(next as isize),
1063                       self.vec.as_mut_ptr().offset(idx as isize),
1064                       len - next);
1065             self.vec.set_len(len - (next - idx));
1066         }
1067         ch
1068     }
1069
1070     /// Retains only the characters specified by the predicate.
1071     ///
1072     /// In other words, remove all characters `c` such that `f(c)` returns `false`.
1073     /// This method operates in place and preserves the order of the retained
1074     /// characters.
1075     ///
1076     /// # Examples
1077     ///
1078     /// ```
1079     /// #![feature(string_retain)]
1080     ///
1081     /// let mut s = String::from("f_o_ob_ar");
1082     ///
1083     /// s.retain(|c| c != '_');
1084     ///
1085     /// assert_eq!(s, "foobar");
1086     /// ```
1087     #[inline]
1088     #[unstable(feature = "string_retain", issue = "43874")]
1089     pub fn retain<F>(&mut self, mut f: F)
1090         where F: FnMut(char) -> bool
1091     {
1092         let len = self.len();
1093         let mut del_bytes = 0;
1094         let mut idx = 0;
1095
1096         while idx < len {
1097             let ch = unsafe {
1098                 self.slice_unchecked(idx, len).chars().next().unwrap()
1099             };
1100             let ch_len = ch.len_utf8();
1101
1102             if !f(ch) {
1103                 del_bytes += ch_len;
1104             } else if del_bytes > 0 {
1105                 unsafe {
1106                     ptr::copy(self.vec.as_ptr().offset(idx as isize),
1107                               self.vec.as_mut_ptr().offset((idx - del_bytes) as isize),
1108                               ch_len);
1109                 }
1110             }
1111
1112             // Point idx to the next char
1113             idx += ch_len;
1114         }
1115
1116         if del_bytes > 0 {
1117             unsafe { self.vec.set_len(len - del_bytes); }
1118         }
1119     }
1120
1121     /// Inserts a character into this `String` at a byte position.
1122     ///
1123     /// This is an `O(n)` operation as it requires copying every element in the
1124     /// buffer.
1125     ///
1126     /// # Panics
1127     ///
1128     /// Panics if `idx` is larger than the `String`'s length, or if it does not
1129     /// lie on a [`char`] boundary.
1130     ///
1131     /// [`char`]: ../../std/primitive.char.html
1132     ///
1133     /// # Examples
1134     ///
1135     /// Basic usage:
1136     ///
1137     /// ```
1138     /// let mut s = String::with_capacity(3);
1139     ///
1140     /// s.insert(0, 'f');
1141     /// s.insert(1, 'o');
1142     /// s.insert(2, 'o');
1143     ///
1144     /// assert_eq!("foo", s);
1145     /// ```
1146     #[inline]
1147     #[stable(feature = "rust1", since = "1.0.0")]
1148     pub fn insert(&mut self, idx: usize, ch: char) {
1149         assert!(self.is_char_boundary(idx));
1150         let mut bits = [0; 4];
1151         let bits = ch.encode_utf8(&mut bits).as_bytes();
1152
1153         unsafe {
1154             self.insert_bytes(idx, bits);
1155         }
1156     }
1157
1158     unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
1159         let len = self.len();
1160         let amt = bytes.len();
1161         self.vec.reserve(amt);
1162
1163         ptr::copy(self.vec.as_ptr().offset(idx as isize),
1164                   self.vec.as_mut_ptr().offset((idx + amt) as isize),
1165                   len - idx);
1166         ptr::copy(bytes.as_ptr(),
1167                   self.vec.as_mut_ptr().offset(idx as isize),
1168                   amt);
1169         self.vec.set_len(len + amt);
1170     }
1171
1172     /// Inserts a string slice into this `String` at a byte position.
1173     ///
1174     /// This is an `O(n)` operation as it requires copying every element in the
1175     /// buffer.
1176     ///
1177     /// # Panics
1178     ///
1179     /// Panics if `idx` is larger than the `String`'s length, or if it does not
1180     /// lie on a [`char`] boundary.
1181     ///
1182     /// [`char`]: ../../std/primitive.char.html
1183     ///
1184     /// # Examples
1185     ///
1186     /// Basic usage:
1187     ///
1188     /// ```
1189     /// let mut s = String::from("bar");
1190     ///
1191     /// s.insert_str(0, "foo");
1192     ///
1193     /// assert_eq!("foobar", s);
1194     /// ```
1195     #[inline]
1196     #[stable(feature = "insert_str", since = "1.16.0")]
1197     pub fn insert_str(&mut self, idx: usize, string: &str) {
1198         assert!(self.is_char_boundary(idx));
1199
1200         unsafe {
1201             self.insert_bytes(idx, string.as_bytes());
1202         }
1203     }
1204
1205     /// Returns a mutable reference to the contents of this `String`.
1206     ///
1207     /// # Safety
1208     ///
1209     /// This function is unsafe because it does not check that the bytes passed
1210     /// to it are valid UTF-8. If this constraint is violated, it may cause
1211     /// memory unsafety issues with future users of the `String`, as the rest of
1212     /// the standard library assumes that `String`s are valid UTF-8.
1213     ///
1214     /// # Examples
1215     ///
1216     /// Basic usage:
1217     ///
1218     /// ```
1219     /// let mut s = String::from("hello");
1220     ///
1221     /// unsafe {
1222     ///     let vec = s.as_mut_vec();
1223     ///     assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1224     ///
1225     ///     vec.reverse();
1226     /// }
1227     /// assert_eq!(s, "olleh");
1228     /// ```
1229     #[inline]
1230     #[stable(feature = "rust1", since = "1.0.0")]
1231     pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1232         &mut self.vec
1233     }
1234
1235     /// Returns the length of this `String`, in bytes.
1236     ///
1237     /// # Examples
1238     ///
1239     /// Basic usage:
1240     ///
1241     /// ```
1242     /// let a = String::from("foo");
1243     ///
1244     /// assert_eq!(a.len(), 3);
1245     /// ```
1246     #[inline]
1247     #[stable(feature = "rust1", since = "1.0.0")]
1248     pub fn len(&self) -> usize {
1249         self.vec.len()
1250     }
1251
1252     /// Returns `true` if this `String` has a length of zero.
1253     ///
1254     /// Returns `false` otherwise.
1255     ///
1256     /// # Examples
1257     ///
1258     /// Basic usage:
1259     ///
1260     /// ```
1261     /// let mut v = String::new();
1262     /// assert!(v.is_empty());
1263     ///
1264     /// v.push('a');
1265     /// assert!(!v.is_empty());
1266     /// ```
1267     #[inline]
1268     #[stable(feature = "rust1", since = "1.0.0")]
1269     pub fn is_empty(&self) -> bool {
1270         self.len() == 0
1271     }
1272
1273     /// Splits the string into two at the given index.
1274     ///
1275     /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1276     /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1277     /// boundary of a UTF-8 code point.
1278     ///
1279     /// Note that the capacity of `self` does not change.
1280     ///
1281     /// # Panics
1282     ///
1283     /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1284     /// code point of the string.
1285     ///
1286     /// # Examples
1287     ///
1288     /// ```
1289     /// # fn main() {
1290     /// let mut hello = String::from("Hello, World!");
1291     /// let world = hello.split_off(7);
1292     /// assert_eq!(hello, "Hello, ");
1293     /// assert_eq!(world, "World!");
1294     /// # }
1295     /// ```
1296     #[inline]
1297     #[stable(feature = "string_split_off", since = "1.16.0")]
1298     pub fn split_off(&mut self, at: usize) -> String {
1299         assert!(self.is_char_boundary(at));
1300         let other = self.vec.split_off(at);
1301         unsafe { String::from_utf8_unchecked(other) }
1302     }
1303
1304     /// Truncates this `String`, removing all contents.
1305     ///
1306     /// While this means the `String` will have a length of zero, it does not
1307     /// touch its capacity.
1308     ///
1309     /// # Examples
1310     ///
1311     /// Basic usage:
1312     ///
1313     /// ```
1314     /// let mut s = String::from("foo");
1315     ///
1316     /// s.clear();
1317     ///
1318     /// assert!(s.is_empty());
1319     /// assert_eq!(0, s.len());
1320     /// assert_eq!(3, s.capacity());
1321     /// ```
1322     #[inline]
1323     #[stable(feature = "rust1", since = "1.0.0")]
1324     pub fn clear(&mut self) {
1325         self.vec.clear()
1326     }
1327
1328     /// Creates a draining iterator that removes the specified range in the string
1329     /// and yields the removed chars.
1330     ///
1331     /// Note: The element range is removed even if the iterator is not
1332     /// consumed until the end.
1333     ///
1334     /// # Panics
1335     ///
1336     /// Panics if the starting point or end point do not lie on a [`char`]
1337     /// boundary, or if they're out of bounds.
1338     ///
1339     /// [`char`]: ../../std/primitive.char.html
1340     ///
1341     /// # Examples
1342     ///
1343     /// Basic usage:
1344     ///
1345     /// ```
1346     /// let mut s = String::from("α is alpha, β is beta");
1347     /// let beta_offset = s.find('β').unwrap_or(s.len());
1348     ///
1349     /// // Remove the range up until the β from the string
1350     /// let t: String = s.drain(..beta_offset).collect();
1351     /// assert_eq!(t, "α is alpha, ");
1352     /// assert_eq!(s, "β is beta");
1353     ///
1354     /// // A full range clears the string
1355     /// s.drain(..);
1356     /// assert_eq!(s, "");
1357     /// ```
1358     #[stable(feature = "drain", since = "1.6.0")]
1359     pub fn drain<R>(&mut self, range: R) -> Drain
1360         where R: RangeArgument<usize>
1361     {
1362         // Memory safety
1363         //
1364         // The String version of Drain does not have the memory safety issues
1365         // of the vector version. The data is just plain bytes.
1366         // Because the range removal happens in Drop, if the Drain iterator is leaked,
1367         // the removal will not happen.
1368         let len = self.len();
1369         let start = match range.start() {
1370             Included(&n) => n,
1371             Excluded(&n) => n + 1,
1372             Unbounded => 0,
1373         };
1374         let end = match range.end() {
1375             Included(&n) => n + 1,
1376             Excluded(&n) => n,
1377             Unbounded => len,
1378         };
1379
1380         // Take out two simultaneous borrows. The &mut String won't be accessed
1381         // until iteration is over, in Drop.
1382         let self_ptr = self as *mut _;
1383         // slicing does the appropriate bounds checks
1384         let chars_iter = self[start..end].chars();
1385
1386         Drain {
1387             start,
1388             end,
1389             iter: chars_iter,
1390             string: self_ptr,
1391         }
1392     }
1393
1394     /// Creates a splicing iterator that removes the specified range in the string,
1395     /// replaces with the given string, and yields the removed chars.
1396     /// The given string doesn’t need to be the same length as the range.
1397     ///
1398     /// Note: The element range is removed when the [`Splice`] is dropped,
1399     /// even if the iterator is not consumed until the end.
1400     ///
1401     /// # Panics
1402     ///
1403     /// Panics if the starting point or end point do not lie on a [`char`]
1404     /// boundary, or if they're out of bounds.
1405     ///
1406     /// [`char`]: ../../std/primitive.char.html
1407     /// [`Splice`]: ../../std/string/struct.Splice.html
1408     ///
1409     /// # Examples
1410     ///
1411     /// Basic usage:
1412     ///
1413     /// ```
1414     /// #![feature(splice)]
1415     /// let mut s = String::from("α is alpha, β is beta");
1416     /// let beta_offset = s.find('β').unwrap_or(s.len());
1417     ///
1418     /// // Replace the range up until the β from the string
1419     /// let t: String = s.splice(..beta_offset, "Α is capital alpha; ").collect();
1420     /// assert_eq!(t, "α is alpha, ");
1421     /// assert_eq!(s, "Α is capital alpha; β is beta");
1422     /// ```
1423     #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
1424     pub fn splice<'a, 'b, R>(&'a mut self, range: R, replace_with: &'b str) -> Splice<'a, 'b>
1425         where R: RangeArgument<usize>
1426     {
1427         // Memory safety
1428         //
1429         // The String version of Splice does not have the memory safety issues
1430         // of the vector version. The data is just plain bytes.
1431         // Because the range removal happens in Drop, if the Splice iterator is leaked,
1432         // the removal will not happen.
1433         let len = self.len();
1434         let start = match range.start() {
1435              Included(&n) => n,
1436              Excluded(&n) => n + 1,
1437              Unbounded => 0,
1438         };
1439         let end = match range.end() {
1440              Included(&n) => n + 1,
1441              Excluded(&n) => n,
1442              Unbounded => len,
1443         };
1444
1445         // Take out two simultaneous borrows. The &mut String won't be accessed
1446         // until iteration is over, in Drop.
1447         let self_ptr = self as *mut _;
1448         // slicing does the appropriate bounds checks
1449         let chars_iter = self[start..end].chars();
1450
1451         Splice {
1452             start,
1453             end,
1454             iter: chars_iter,
1455             string: self_ptr,
1456             replace_with,
1457         }
1458     }
1459
1460     /// Converts this `String` into a [`Box`]`<`[`str`]`>`.
1461     ///
1462     /// This will drop any excess capacity.
1463     ///
1464     /// [`Box`]: ../../std/boxed/struct.Box.html
1465     /// [`str`]: ../../std/primitive.str.html
1466     ///
1467     /// # Examples
1468     ///
1469     /// Basic usage:
1470     ///
1471     /// ```
1472     /// let s = String::from("hello");
1473     ///
1474     /// let b = s.into_boxed_str();
1475     /// ```
1476     #[stable(feature = "box_str", since = "1.4.0")]
1477     pub fn into_boxed_str(self) -> Box<str> {
1478         let slice = self.vec.into_boxed_slice();
1479         unsafe { from_boxed_utf8_unchecked(slice) }
1480     }
1481 }
1482
1483 impl FromUtf8Error {
1484     /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
1485     ///
1486     /// # Examples
1487     ///
1488     /// Basic usage:
1489     ///
1490     /// ```
1491     /// #![feature(from_utf8_error_as_bytes)]
1492     /// // some invalid bytes, in a vector
1493     /// let bytes = vec![0, 159];
1494     ///
1495     /// let value = String::from_utf8(bytes);
1496     ///
1497     /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1498     /// ```
1499     #[unstable(feature = "from_utf8_error_as_bytes", reason = "recently added", issue = "40895")]
1500     pub fn as_bytes(&self) -> &[u8] {
1501         &self.bytes[..]
1502     }
1503
1504     /// Returns the bytes that were attempted to convert to a `String`.
1505     ///
1506     /// This method is carefully constructed to avoid allocation. It will
1507     /// consume the error, moving out the bytes, so that a copy of the bytes
1508     /// does not need to be made.
1509     ///
1510     /// # Examples
1511     ///
1512     /// Basic usage:
1513     ///
1514     /// ```
1515     /// // some invalid bytes, in a vector
1516     /// let bytes = vec![0, 159];
1517     ///
1518     /// let value = String::from_utf8(bytes);
1519     ///
1520     /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1521     /// ```
1522     #[stable(feature = "rust1", since = "1.0.0")]
1523     pub fn into_bytes(self) -> Vec<u8> {
1524         self.bytes
1525     }
1526
1527     /// Fetch a `Utf8Error` to get more details about the conversion failure.
1528     ///
1529     /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1530     /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1531     /// an analogue to `FromUtf8Error`. See its documentation for more details
1532     /// on using it.
1533     ///
1534     /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
1535     /// [`std::str`]: ../../std/str/index.html
1536     /// [`u8`]: ../../std/primitive.u8.html
1537     /// [`&str`]: ../../std/primitive.str.html
1538     ///
1539     /// # Examples
1540     ///
1541     /// Basic usage:
1542     ///
1543     /// ```
1544     /// // some invalid bytes, in a vector
1545     /// let bytes = vec![0, 159];
1546     ///
1547     /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1548     ///
1549     /// // the first byte is invalid here
1550     /// assert_eq!(1, error.valid_up_to());
1551     /// ```
1552     #[stable(feature = "rust1", since = "1.0.0")]
1553     pub fn utf8_error(&self) -> Utf8Error {
1554         self.error
1555     }
1556 }
1557
1558 #[stable(feature = "rust1", since = "1.0.0")]
1559 impl fmt::Display for FromUtf8Error {
1560     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1561         fmt::Display::fmt(&self.error, f)
1562     }
1563 }
1564
1565 #[stable(feature = "rust1", since = "1.0.0")]
1566 impl fmt::Display for FromUtf16Error {
1567     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1568         fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1569     }
1570 }
1571
1572 #[stable(feature = "rust1", since = "1.0.0")]
1573 impl Clone for String {
1574     fn clone(&self) -> Self {
1575         String { vec: self.vec.clone() }
1576     }
1577
1578     fn clone_from(&mut self, source: &Self) {
1579         self.vec.clone_from(&source.vec);
1580     }
1581 }
1582
1583 #[stable(feature = "rust1", since = "1.0.0")]
1584 impl FromIterator<char> for String {
1585     fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1586         let mut buf = String::new();
1587         buf.extend(iter);
1588         buf
1589     }
1590 }
1591
1592 #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
1593 impl<'a> FromIterator<&'a char> for String {
1594     fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
1595         let mut buf = String::new();
1596         buf.extend(iter);
1597         buf
1598     }
1599 }
1600
1601 #[stable(feature = "rust1", since = "1.0.0")]
1602 impl<'a> FromIterator<&'a str> for String {
1603     fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1604         let mut buf = String::new();
1605         buf.extend(iter);
1606         buf
1607     }
1608 }
1609
1610 #[stable(feature = "extend_string", since = "1.4.0")]
1611 impl FromIterator<String> for String {
1612     fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1613         let mut buf = String::new();
1614         buf.extend(iter);
1615         buf
1616     }
1617 }
1618
1619 #[stable(feature = "herd_cows", since = "1.19.0")]
1620 impl<'a> FromIterator<Cow<'a, str>> for String {
1621     fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> String {
1622         let mut buf = String::new();
1623         buf.extend(iter);
1624         buf
1625     }
1626 }
1627
1628 #[stable(feature = "rust1", since = "1.0.0")]
1629 impl Extend<char> for String {
1630     fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1631         let iterator = iter.into_iter();
1632         let (lower_bound, _) = iterator.size_hint();
1633         self.reserve(lower_bound);
1634         for ch in iterator {
1635             self.push(ch)
1636         }
1637     }
1638 }
1639
1640 #[stable(feature = "extend_ref", since = "1.2.0")]
1641 impl<'a> Extend<&'a char> for String {
1642     fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1643         self.extend(iter.into_iter().cloned());
1644     }
1645 }
1646
1647 #[stable(feature = "rust1", since = "1.0.0")]
1648 impl<'a> Extend<&'a str> for String {
1649     fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1650         for s in iter {
1651             self.push_str(s)
1652         }
1653     }
1654 }
1655
1656 #[stable(feature = "extend_string", since = "1.4.0")]
1657 impl Extend<String> for String {
1658     fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1659         for s in iter {
1660             self.push_str(&s)
1661         }
1662     }
1663 }
1664
1665 #[stable(feature = "herd_cows", since = "1.19.0")]
1666 impl<'a> Extend<Cow<'a, str>> for String {
1667     fn extend<I: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: I) {
1668         for s in iter {
1669             self.push_str(&s)
1670         }
1671     }
1672 }
1673
1674 /// A convenience impl that delegates to the impl for `&str`
1675 #[unstable(feature = "pattern",
1676            reason = "API not fully fleshed out and ready to be stabilized",
1677            issue = "27721")]
1678 impl<'a, 'b> Pattern<'a> for &'b String {
1679     type Searcher = <&'b str as Pattern<'a>>::Searcher;
1680
1681     fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1682         self[..].into_searcher(haystack)
1683     }
1684
1685     #[inline]
1686     fn is_contained_in(self, haystack: &'a str) -> bool {
1687         self[..].is_contained_in(haystack)
1688     }
1689
1690     #[inline]
1691     fn is_prefix_of(self, haystack: &'a str) -> bool {
1692         self[..].is_prefix_of(haystack)
1693     }
1694 }
1695
1696 #[stable(feature = "rust1", since = "1.0.0")]
1697 impl PartialEq for String {
1698     #[inline]
1699     fn eq(&self, other: &String) -> bool {
1700         PartialEq::eq(&self[..], &other[..])
1701     }
1702     #[inline]
1703     fn ne(&self, other: &String) -> bool {
1704         PartialEq::ne(&self[..], &other[..])
1705     }
1706 }
1707
1708 macro_rules! impl_eq {
1709     ($lhs:ty, $rhs: ty) => {
1710         #[stable(feature = "rust1", since = "1.0.0")]
1711         impl<'a, 'b> PartialEq<$rhs> for $lhs {
1712             #[inline]
1713             fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1714             #[inline]
1715             fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1716         }
1717
1718         #[stable(feature = "rust1", since = "1.0.0")]
1719         impl<'a, 'b> PartialEq<$lhs> for $rhs {
1720             #[inline]
1721             fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1722             #[inline]
1723             fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1724         }
1725
1726     }
1727 }
1728
1729 impl_eq! { String, str }
1730 impl_eq! { String, &'a str }
1731 impl_eq! { Cow<'a, str>, str }
1732 impl_eq! { Cow<'a, str>, &'b str }
1733 impl_eq! { Cow<'a, str>, String }
1734
1735 #[stable(feature = "rust1", since = "1.0.0")]
1736 impl Default for String {
1737     /// Creates an empty `String`.
1738     #[inline]
1739     fn default() -> String {
1740         String::new()
1741     }
1742 }
1743
1744 #[stable(feature = "rust1", since = "1.0.0")]
1745 impl fmt::Display for String {
1746     #[inline]
1747     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1748         fmt::Display::fmt(&**self, f)
1749     }
1750 }
1751
1752 #[stable(feature = "rust1", since = "1.0.0")]
1753 impl fmt::Debug for String {
1754     #[inline]
1755     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1756         fmt::Debug::fmt(&**self, f)
1757     }
1758 }
1759
1760 #[stable(feature = "rust1", since = "1.0.0")]
1761 impl hash::Hash for String {
1762     #[inline]
1763     fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1764         (**self).hash(hasher)
1765     }
1766 }
1767
1768 /// Implements the `+` operator for concatenating two strings.
1769 ///
1770 /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
1771 /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
1772 /// every operation, which would lead to `O(n^2)` running time when building an `n`-byte string by
1773 /// repeated concatenation.
1774 ///
1775 /// The string on the right-hand side is only borrowed; its contents are copied into the returned
1776 /// `String`.
1777 ///
1778 /// # Examples
1779 ///
1780 /// Concatenating two `String`s takes the first by value and borrows the second:
1781 ///
1782 /// ```
1783 /// let a = String::from("hello");
1784 /// let b = String::from(" world");
1785 /// let c = a + &b;
1786 /// // `a` is moved and can no longer be used here.
1787 /// ```
1788 ///
1789 /// If you want to keep using the first `String`, you can clone it and append to the clone instead:
1790 ///
1791 /// ```
1792 /// let a = String::from("hello");
1793 /// let b = String::from(" world");
1794 /// let c = a.clone() + &b;
1795 /// // `a` is still valid here.
1796 /// ```
1797 ///
1798 /// Concatenating `&str` slices can be done by converting the first to a `String`:
1799 ///
1800 /// ```
1801 /// let a = "hello";
1802 /// let b = " world";
1803 /// let c = a.to_string() + b;
1804 /// ```
1805 #[stable(feature = "rust1", since = "1.0.0")]
1806 impl<'a> Add<&'a str> for String {
1807     type Output = String;
1808
1809     #[inline]
1810     fn add(mut self, other: &str) -> String {
1811         self.push_str(other);
1812         self
1813     }
1814 }
1815
1816 /// Implements the `+=` operator for appending to a `String`.
1817 ///
1818 /// This has the same behavior as the [`push_str`] method.
1819 ///
1820 /// [`push_str`]: struct.String.html#method.push_str
1821 #[stable(feature = "stringaddassign", since = "1.12.0")]
1822 impl<'a> AddAssign<&'a str> for String {
1823     #[inline]
1824     fn add_assign(&mut self, other: &str) {
1825         self.push_str(other);
1826     }
1827 }
1828
1829 #[stable(feature = "rust1", since = "1.0.0")]
1830 impl ops::Index<ops::Range<usize>> for String {
1831     type Output = str;
1832
1833     #[inline]
1834     fn index(&self, index: ops::Range<usize>) -> &str {
1835         &self[..][index]
1836     }
1837 }
1838 #[stable(feature = "rust1", since = "1.0.0")]
1839 impl ops::Index<ops::RangeTo<usize>> for String {
1840     type Output = str;
1841
1842     #[inline]
1843     fn index(&self, index: ops::RangeTo<usize>) -> &str {
1844         &self[..][index]
1845     }
1846 }
1847 #[stable(feature = "rust1", since = "1.0.0")]
1848 impl ops::Index<ops::RangeFrom<usize>> for String {
1849     type Output = str;
1850
1851     #[inline]
1852     fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1853         &self[..][index]
1854     }
1855 }
1856 #[stable(feature = "rust1", since = "1.0.0")]
1857 impl ops::Index<ops::RangeFull> for String {
1858     type Output = str;
1859
1860     #[inline]
1861     fn index(&self, _index: ops::RangeFull) -> &str {
1862         unsafe { str::from_utf8_unchecked(&self.vec) }
1863     }
1864 }
1865 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1866 impl ops::Index<ops::RangeInclusive<usize>> for String {
1867     type Output = str;
1868
1869     #[inline]
1870     fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1871         Index::index(&**self, index)
1872     }
1873 }
1874 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1875 impl ops::Index<ops::RangeToInclusive<usize>> for String {
1876     type Output = str;
1877
1878     #[inline]
1879     fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1880         Index::index(&**self, index)
1881     }
1882 }
1883
1884 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1885 impl ops::IndexMut<ops::Range<usize>> for String {
1886     #[inline]
1887     fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1888         &mut self[..][index]
1889     }
1890 }
1891 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1892 impl ops::IndexMut<ops::RangeTo<usize>> for String {
1893     #[inline]
1894     fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1895         &mut self[..][index]
1896     }
1897 }
1898 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1899 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
1900     #[inline]
1901     fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1902         &mut self[..][index]
1903     }
1904 }
1905 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1906 impl ops::IndexMut<ops::RangeFull> for String {
1907     #[inline]
1908     fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1909         unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
1910     }
1911 }
1912 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1913 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
1914     #[inline]
1915     fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
1916         IndexMut::index_mut(&mut **self, index)
1917     }
1918 }
1919 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1920 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
1921     #[inline]
1922     fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
1923         IndexMut::index_mut(&mut **self, index)
1924     }
1925 }
1926
1927 #[stable(feature = "rust1", since = "1.0.0")]
1928 impl ops::Deref for String {
1929     type Target = str;
1930
1931     #[inline]
1932     fn deref(&self) -> &str {
1933         unsafe { str::from_utf8_unchecked(&self.vec) }
1934     }
1935 }
1936
1937 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1938 impl ops::DerefMut for String {
1939     #[inline]
1940     fn deref_mut(&mut self) -> &mut str {
1941         unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
1942     }
1943 }
1944
1945 /// An error when parsing a `String`.
1946 ///
1947 /// This `enum` is slightly awkward: it will never actually exist. This error is
1948 /// part of the type signature of the implementation of [`FromStr`] on
1949 /// [`String`]. The return type of [`from_str`], requires that an error be
1950 /// defined, but, given that a [`String`] can always be made into a new
1951 /// [`String`] without error, this type will never actually be returned. As
1952 /// such, it is only here to satisfy said signature, and is useless otherwise.
1953 ///
1954 /// [`FromStr`]: ../../std/str/trait.FromStr.html
1955 /// [`String`]: struct.String.html
1956 /// [`from_str`]: ../../std/str/trait.FromStr.html#tymethod.from_str
1957 #[stable(feature = "str_parse_error", since = "1.5.0")]
1958 #[derive(Copy)]
1959 pub enum ParseError {}
1960
1961 #[stable(feature = "rust1", since = "1.0.0")]
1962 impl FromStr for String {
1963     type Err = ParseError;
1964     #[inline]
1965     fn from_str(s: &str) -> Result<String, ParseError> {
1966         Ok(String::from(s))
1967     }
1968 }
1969
1970 #[stable(feature = "str_parse_error", since = "1.5.0")]
1971 impl Clone for ParseError {
1972     fn clone(&self) -> ParseError {
1973         match *self {}
1974     }
1975 }
1976
1977 #[stable(feature = "str_parse_error", since = "1.5.0")]
1978 impl fmt::Debug for ParseError {
1979     fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1980         match *self {}
1981     }
1982 }
1983
1984 #[stable(feature = "str_parse_error2", since = "1.8.0")]
1985 impl fmt::Display for ParseError {
1986     fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1987         match *self {}
1988     }
1989 }
1990
1991 #[stable(feature = "str_parse_error", since = "1.5.0")]
1992 impl PartialEq for ParseError {
1993     fn eq(&self, _: &ParseError) -> bool {
1994         match *self {}
1995     }
1996 }
1997
1998 #[stable(feature = "str_parse_error", since = "1.5.0")]
1999 impl Eq for ParseError {}
2000
2001 /// A trait for converting a value to a `String`.
2002 ///
2003 /// This trait is automatically implemented for any type which implements the
2004 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
2005 /// [`Display`] should be implemented instead, and you get the `ToString`
2006 /// implementation for free.
2007 ///
2008 /// [`Display`]: ../../std/fmt/trait.Display.html
2009 #[stable(feature = "rust1", since = "1.0.0")]
2010 pub trait ToString {
2011     /// Converts the given value to a `String`.
2012     ///
2013     /// # Examples
2014     ///
2015     /// Basic usage:
2016     ///
2017     /// ```
2018     /// let i = 5;
2019     /// let five = String::from("5");
2020     ///
2021     /// assert_eq!(five, i.to_string());
2022     /// ```
2023     #[stable(feature = "rust1", since = "1.0.0")]
2024     fn to_string(&self) -> String;
2025 }
2026
2027 /// # Panics
2028 ///
2029 /// In this implementation, the `to_string` method panics
2030 /// if the `Display` implementation returns an error.
2031 /// This indicates an incorrect `Display` implementation
2032 /// since `fmt::Write for String` never returns an error itself.
2033 #[stable(feature = "rust1", since = "1.0.0")]
2034 impl<T: fmt::Display + ?Sized> ToString for T {
2035     #[inline]
2036     default fn to_string(&self) -> String {
2037         use core::fmt::Write;
2038         let mut buf = String::new();
2039         buf.write_fmt(format_args!("{}", self))
2040            .expect("a Display implementation return an error unexpectedly");
2041         buf.shrink_to_fit();
2042         buf
2043     }
2044 }
2045
2046 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
2047 impl ToString for str {
2048     #[inline]
2049     fn to_string(&self) -> String {
2050         String::from(self)
2051     }
2052 }
2053
2054 #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")]
2055 impl<'a> ToString for Cow<'a, str> {
2056     #[inline]
2057     fn to_string(&self) -> String {
2058         self[..].to_owned()
2059     }
2060 }
2061
2062 #[stable(feature = "string_to_string_specialization", since = "1.17.0")]
2063 impl ToString for String {
2064     #[inline]
2065     fn to_string(&self) -> String {
2066         self.to_owned()
2067     }
2068 }
2069
2070 #[stable(feature = "rust1", since = "1.0.0")]
2071 impl AsRef<str> for String {
2072     #[inline]
2073     fn as_ref(&self) -> &str {
2074         self
2075     }
2076 }
2077
2078 #[stable(feature = "rust1", since = "1.0.0")]
2079 impl AsRef<[u8]> for String {
2080     #[inline]
2081     fn as_ref(&self) -> &[u8] {
2082         self.as_bytes()
2083     }
2084 }
2085
2086 #[stable(feature = "rust1", since = "1.0.0")]
2087 impl<'a> From<&'a str> for String {
2088     fn from(s: &'a str) -> String {
2089         s.to_owned()
2090     }
2091 }
2092
2093 // note: test pulls in libstd, which causes errors here
2094 #[cfg(not(test))]
2095 #[stable(feature = "string_from_box", since = "1.18.0")]
2096 impl From<Box<str>> for String {
2097     fn from(s: Box<str>) -> String {
2098         s.into_string()
2099     }
2100 }
2101
2102 #[stable(feature = "box_from_str", since = "1.20.0")]
2103 impl From<String> for Box<str> {
2104     fn from(s: String) -> Box<str> {
2105         s.into_boxed_str()
2106     }
2107 }
2108
2109 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
2110 impl<'a> From<Cow<'a, str>> for String {
2111     fn from(s: Cow<'a, str>) -> String {
2112         s.into_owned()
2113     }
2114 }
2115
2116 #[stable(feature = "rust1", since = "1.0.0")]
2117 impl<'a> From<&'a str> for Cow<'a, str> {
2118     #[inline]
2119     fn from(s: &'a str) -> Cow<'a, str> {
2120         Cow::Borrowed(s)
2121     }
2122 }
2123
2124 #[stable(feature = "rust1", since = "1.0.0")]
2125 impl<'a> From<String> for Cow<'a, str> {
2126     #[inline]
2127     fn from(s: String) -> Cow<'a, str> {
2128         Cow::Owned(s)
2129     }
2130 }
2131
2132 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2133 impl<'a> FromIterator<char> for Cow<'a, str> {
2134     fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
2135         Cow::Owned(FromIterator::from_iter(it))
2136     }
2137 }
2138
2139 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2140 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
2141     fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
2142         Cow::Owned(FromIterator::from_iter(it))
2143     }
2144 }
2145
2146 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2147 impl<'a> FromIterator<String> for Cow<'a, str> {
2148     fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
2149         Cow::Owned(FromIterator::from_iter(it))
2150     }
2151 }
2152
2153 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
2154 impl From<String> for Vec<u8> {
2155     fn from(string: String) -> Vec<u8> {
2156         string.into_bytes()
2157     }
2158 }
2159
2160 #[stable(feature = "rust1", since = "1.0.0")]
2161 impl fmt::Write for String {
2162     #[inline]
2163     fn write_str(&mut self, s: &str) -> fmt::Result {
2164         self.push_str(s);
2165         Ok(())
2166     }
2167
2168     #[inline]
2169     fn write_char(&mut self, c: char) -> fmt::Result {
2170         self.push(c);
2171         Ok(())
2172     }
2173 }
2174
2175 /// A draining iterator for `String`.
2176 ///
2177 /// This struct is created by the [`drain`] method on [`String`]. See its
2178 /// documentation for more.
2179 ///
2180 /// [`drain`]: struct.String.html#method.drain
2181 /// [`String`]: struct.String.html
2182 #[stable(feature = "drain", since = "1.6.0")]
2183 pub struct Drain<'a> {
2184     /// Will be used as &'a mut String in the destructor
2185     string: *mut String,
2186     /// Start of part to remove
2187     start: usize,
2188     /// End of part to remove
2189     end: usize,
2190     /// Current remaining range to remove
2191     iter: Chars<'a>,
2192 }
2193
2194 #[stable(feature = "collection_debug", since = "1.17.0")]
2195 impl<'a> fmt::Debug for Drain<'a> {
2196     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2197         f.pad("Drain { .. }")
2198     }
2199 }
2200
2201 #[stable(feature = "drain", since = "1.6.0")]
2202 unsafe impl<'a> Sync for Drain<'a> {}
2203 #[stable(feature = "drain", since = "1.6.0")]
2204 unsafe impl<'a> Send for Drain<'a> {}
2205
2206 #[stable(feature = "drain", since = "1.6.0")]
2207 impl<'a> Drop for Drain<'a> {
2208     fn drop(&mut self) {
2209         unsafe {
2210             // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2211             // panic code being inserted again.
2212             let self_vec = (*self.string).as_mut_vec();
2213             if self.start <= self.end && self.end <= self_vec.len() {
2214                 self_vec.drain(self.start..self.end);
2215             }
2216         }
2217     }
2218 }
2219
2220 #[stable(feature = "drain", since = "1.6.0")]
2221 impl<'a> Iterator for Drain<'a> {
2222     type Item = char;
2223
2224     #[inline]
2225     fn next(&mut self) -> Option<char> {
2226         self.iter.next()
2227     }
2228
2229     fn size_hint(&self) -> (usize, Option<usize>) {
2230         self.iter.size_hint()
2231     }
2232 }
2233
2234 #[stable(feature = "drain", since = "1.6.0")]
2235 impl<'a> DoubleEndedIterator for Drain<'a> {
2236     #[inline]
2237     fn next_back(&mut self) -> Option<char> {
2238         self.iter.next_back()
2239     }
2240 }
2241
2242 #[unstable(feature = "fused", issue = "35602")]
2243 impl<'a> FusedIterator for Drain<'a> {}
2244
2245 /// A splicing iterator for `String`.
2246 ///
2247 /// This struct is created by the [`splice()`] method on [`String`]. See its
2248 /// documentation for more.
2249 ///
2250 /// [`splice()`]: struct.String.html#method.splice
2251 /// [`String`]: struct.String.html
2252 #[derive(Debug)]
2253 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2254 pub struct Splice<'a, 'b> {
2255     /// Will be used as &'a mut String in the destructor
2256     string: *mut String,
2257     /// Start of part to remove
2258     start: usize,
2259     /// End of part to remove
2260     end: usize,
2261     /// Current remaining range to remove
2262     iter: Chars<'a>,
2263     replace_with: &'b str,
2264 }
2265
2266 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2267 unsafe impl<'a, 'b> Sync for Splice<'a, 'b> {}
2268 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2269 unsafe impl<'a, 'b> Send for Splice<'a, 'b> {}
2270
2271 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2272 impl<'a, 'b> Drop for Splice<'a, 'b> {
2273     fn drop(&mut self) {
2274         unsafe {
2275             let vec = (*self.string).as_mut_vec();
2276             vec.splice(self.start..self.end, self.replace_with.bytes());
2277         }
2278     }
2279 }
2280
2281 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2282 impl<'a, 'b> Iterator for Splice<'a, 'b> {
2283     type Item = char;
2284
2285     #[inline]
2286     fn next(&mut self) -> Option<char> {
2287         self.iter.next()
2288     }
2289
2290     fn size_hint(&self) -> (usize, Option<usize>) {
2291         self.iter.size_hint()
2292     }
2293 }
2294
2295 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2296 impl<'a, 'b> DoubleEndedIterator for Splice<'a, 'b> {
2297     #[inline]
2298     fn next_back(&mut self) -> Option<char> {
2299         self.iter.next_back()
2300     }
2301 }