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