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