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