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