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