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