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