alloc/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
45use core::error::Error;
46use core::iter::FusedIterator;
47#[cfg(not(no_global_oom_handling))]
48use core::iter::from_fn;
49#[cfg(not(no_global_oom_handling))]
50use core::num::Saturating;
51#[cfg(not(no_global_oom_handling))]
52use core::ops::Add;
53#[cfg(not(no_global_oom_handling))]
54use core::ops::AddAssign;
55use core::ops::{self, Range, RangeBounds};
56use core::str::pattern::{Pattern, Utf8Pattern};
57use core::{fmt, hash, ptr, slice};
58
59#[cfg(not(no_global_oom_handling))]
60use crate::alloc::Allocator;
61#[cfg(not(no_global_oom_handling))]
62use crate::borrow::{Cow, ToOwned};
63use crate::boxed::Box;
64use crate::collections::TryReserveError;
65use crate::str::{self, CharIndices, Chars, Utf8Error, from_utf8_unchecked_mut};
66#[cfg(not(no_global_oom_handling))]
67use crate::str::{FromStr, from_boxed_utf8_unchecked};
68use crate::vec::{self, Vec};
69
70/// A UTF-8–encoded, growable string.
71///
72/// `String` is the most common string type. It has ownership over the contents
73/// of the string, stored in a heap-allocated buffer (see [Representation](#representation)).
74/// It is closely related to its borrowed counterpart, the primitive [`str`].
75///
76/// # Examples
77///
78/// You can create a `String` from [a literal string][`&str`] with [`String::from`]:
79///
80/// [`String::from`]: From::from
81///
82/// ```
83/// let hello = String::from("Hello, world!");
84/// ```
85///
86/// You can append a [`char`] to a `String` with the [`push`] method, and
87/// append a [`&str`] with the [`push_str`] method:
88///
89/// ```
90/// let mut hello = String::from("Hello, ");
91///
92/// hello.push('w');
93/// hello.push_str("orld!");
94/// ```
95///
96/// [`push`]: String::push
97/// [`push_str`]: String::push_str
98///
99/// If you have a vector of UTF-8 bytes, you can create a `String` from it with
100/// the [`from_utf8`] method:
101///
102/// ```
103/// // some bytes, in a vector
104/// let sparkle_heart = vec![240, 159, 146, 150];
105///
106/// // We know these bytes are valid, so we'll use `unwrap()`.
107/// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
108///
109/// assert_eq!("💖", sparkle_heart);
110/// ```
111///
112/// [`from_utf8`]: String::from_utf8
113///
114/// # UTF-8
115///
116/// `String`s are always valid UTF-8. If you need a non-UTF-8 string, consider
117/// [`OsString`]. It is similar, but without the UTF-8 constraint. Because UTF-8
118/// is a variable width encoding, `String`s are typically smaller than an array of
119/// the same `char`s:
120///
121/// ```
122/// // `s` is ASCII which represents each `char` as one byte
123/// let s = "hello";
124/// assert_eq!(s.len(), 5);
125///
126/// // A `char` array with the same contents would be longer because
127/// // every `char` is four bytes
128/// let s = ['h', 'e', 'l', 'l', 'o'];
129/// let size: usize = s.into_iter().map(|c| size_of_val(&c)).sum();
130/// assert_eq!(size, 20);
131///
132/// // However, for non-ASCII strings, the difference will be smaller
133/// // and sometimes they are the same
134/// let s = "💖💖💖💖💖";
135/// assert_eq!(s.len(), 20);
136///
137/// let s = ['💖', '💖', '💖', '💖', '💖'];
138/// let size: usize = s.into_iter().map(|c| size_of_val(&c)).sum();
139/// assert_eq!(size, 20);
140/// ```
141///
142/// This raises interesting questions as to how `s[i]` should work.
143/// What should `i` be here? Several options include byte indices and
144/// `char` indices but, because of UTF-8 encoding, only byte indices
145/// would provide constant time indexing. Getting the `i`th `char`, for
146/// example, is available using [`chars`]:
147///
148/// ```
149/// let s = "hello";
150/// let third_character = s.chars().nth(2);
151/// assert_eq!(third_character, Some('l'));
152///
153/// let s = "💖💖💖💖💖";
154/// let third_character = s.chars().nth(2);
155/// assert_eq!(third_character, Some('💖'));
156/// ```
157///
158/// Next, what should `s[i]` return? Because indexing returns a reference
159/// to underlying data it could be `&u8`, `&[u8]`, or something similar.
160/// Since we're only providing one index, `&u8` makes the most sense but that
161/// might not be what the user expects and can be explicitly achieved with
162/// [`as_bytes()`]:
163///
164/// ```
165/// // The first byte is 104 - the byte value of `'h'`
166/// let s = "hello";
167/// assert_eq!(s.as_bytes()[0], 104);
168/// // or
169/// assert_eq!(s.as_bytes()[0], b'h');
170///
171/// // The first byte is 240 which isn't obviously useful
172/// let s = "💖💖💖💖💖";
173/// assert_eq!(s.as_bytes()[0], 240);
174/// ```
175///
176/// Due to these ambiguities/restrictions, indexing with a `usize` is simply
177/// forbidden:
178///
179/// ```compile_fail,E0277
180/// let s = "hello";
181///
182/// // The following will not compile!
183/// println!("The first letter of s is {}", s[0]);
184/// ```
185///
186/// It is more clear, however, how `&s[i..j]` should work (that is,
187/// indexing with a range). It should accept byte indices (to be constant-time)
188/// and return a `&str` which is UTF-8 encoded. This is also called "string slicing".
189/// Note this will panic if the byte indices provided are not character
190/// boundaries - see [`is_char_boundary`] for more details. See the implementations
191/// for [`SliceIndex<str>`] for more details on string slicing. For a non-panicking
192/// version of string slicing, see [`get`].
193///
194/// [`OsString`]: ../../std/ffi/struct.OsString.html "ffi::OsString"
195/// [`SliceIndex<str>`]: core::slice::SliceIndex
196/// [`as_bytes()`]: str::as_bytes
197/// [`get`]: str::get
198/// [`is_char_boundary`]: str::is_char_boundary
199///
200/// The [`bytes`] and [`chars`] methods return iterators over the bytes and
201/// codepoints of the string, respectively. To iterate over codepoints along
202/// with byte indices, use [`char_indices`].
203///
204/// [`bytes`]: str::bytes
205/// [`chars`]: str::chars
206/// [`char_indices`]: str::char_indices
207///
208/// # Deref
209///
210/// `String` implements <code>[Deref]<Target = [str]></code>, and so inherits all of [`str`]'s
211/// methods. In addition, this means that you can pass a `String` to a
212/// function which takes a [`&str`] by using an ampersand (`&`):
213///
214/// ```
215/// fn takes_str(s: &str) { }
216///
217/// let s = String::from("Hello");
218///
219/// takes_str(&s);
220/// ```
221///
222/// This will create a [`&str`] from the `String` and pass it in. This
223/// conversion is very inexpensive, and so generally, functions will accept
224/// [`&str`]s as arguments unless they need a `String` for some specific
225/// reason.
226///
227/// In certain cases Rust doesn't have enough information to make this
228/// conversion, known as [`Deref`] coercion. In the following example a string
229/// slice [`&'a str`][`&str`] implements the trait `TraitExample`, and the function
230/// `example_func` takes anything that implements the trait. In this case Rust
231/// would need to make two implicit conversions, which Rust doesn't have the
232/// means to do. For that reason, the following example will not compile.
233///
234/// ```compile_fail,E0277
235/// trait TraitExample {}
236///
237/// impl<'a> TraitExample for &'a str {}
238///
239/// fn example_func<A: TraitExample>(example_arg: A) {}
240///
241/// let example_string = String::from("example_string");
242/// example_func(&example_string);
243/// ```
244///
245/// There are two options that would work instead. The first would be to
246/// change the line `example_func(&example_string);` to
247/// `example_func(example_string.as_str());`, using the method [`as_str()`]
248/// to explicitly extract the string slice containing the string. The second
249/// way changes `example_func(&example_string);` to
250/// `example_func(&*example_string);`. In this case we are dereferencing a
251/// `String` to a [`str`], then referencing the [`str`] back to
252/// [`&str`]. The second way is more idiomatic, however both work to do the
253/// conversion explicitly rather than relying on the implicit conversion.
254///
255/// # Representation
256///
257/// A `String` is made up of three components: a pointer to some bytes, a
258/// length, and a capacity. The pointer points to the internal buffer which `String`
259/// uses to store its data. The length is the number of bytes currently stored
260/// in the buffer, and the capacity is the size of the buffer in bytes. As such,
261/// the length will always be less than or equal to the capacity.
262///
263/// This buffer is always stored on the heap.
264///
265/// You can look at these with the [`as_ptr`], [`len`], and [`capacity`]
266/// methods:
267///
268/// ```
269/// let story = String::from("Once upon a time...");
270///
271/// // Deconstruct the String into parts.
272/// let (ptr, len, capacity) = story.into_raw_parts();
273///
274/// // story has nineteen bytes
275/// assert_eq!(19, len);
276///
277/// // We can re-build a String out of ptr, len, and capacity. This is all
278/// // unsafe because we are responsible for making sure the components are
279/// // valid:
280/// let s = unsafe { String::from_raw_parts(ptr, len, capacity) } ;
281///
282/// assert_eq!(String::from("Once upon a time..."), s);
283/// ```
284///
285/// [`as_ptr`]: str::as_ptr
286/// [`len`]: String::len
287/// [`capacity`]: String::capacity
288///
289/// If a `String` has enough capacity, adding elements to it will not
290/// re-allocate. For example, consider this program:
291///
292/// ```
293/// let mut s = String::new();
294///
295/// println!("{}", s.capacity());
296///
297/// for _ in 0..5 {
298/// s.push_str("hello");
299/// println!("{}", s.capacity());
300/// }
301/// ```
302///
303/// This will output the following:
304///
305/// ```text
306/// 0
307/// 8
308/// 16
309/// 16
310/// 32
311/// 32
312/// ```
313///
314/// At first, we have no memory allocated at all, but as we append to the
315/// string, it increases its capacity appropriately. If we instead use the
316/// [`with_capacity`] method to allocate the correct capacity initially:
317///
318/// ```
319/// let mut s = String::with_capacity(25);
320///
321/// println!("{}", s.capacity());
322///
323/// for _ in 0..5 {
324/// s.push_str("hello");
325/// println!("{}", s.capacity());
326/// }
327/// ```
328///
329/// [`with_capacity`]: String::with_capacity
330///
331/// We end up with a different output:
332///
333/// ```text
334/// 25
335/// 25
336/// 25
337/// 25
338/// 25
339/// 25
340/// ```
341///
342/// Here, there's no need to allocate more memory inside the loop.
343///
344/// [str]: prim@str "str"
345/// [`str`]: prim@str "str"
346/// [`&str`]: prim@str "&str"
347/// [Deref]: core::ops::Deref "ops::Deref"
348/// [`Deref`]: core::ops::Deref "ops::Deref"
349/// [`as_str()`]: String::as_str
350#[derive(PartialEq, PartialOrd, Eq, Ord)]
351#[stable(feature = "rust1", since = "1.0.0")]
352#[lang = "String"]
353pub struct String {
354 vec: Vec<u8>,
355}
356
357/// A possible error value when converting a `String` from a UTF-8 byte vector.
358///
359/// This type is the error type for the [`from_utf8`] method on [`String`]. It
360/// is designed in such a way to carefully avoid reallocations: the
361/// [`into_bytes`] method will give back the byte vector that was used in the
362/// conversion attempt.
363///
364/// [`from_utf8`]: String::from_utf8
365/// [`into_bytes`]: FromUtf8Error::into_bytes
366///
367/// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
368/// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
369/// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
370/// through the [`utf8_error`] method.
371///
372/// [`Utf8Error`]: str::Utf8Error "std::str::Utf8Error"
373/// [`std::str`]: core::str "std::str"
374/// [`&str`]: prim@str "&str"
375/// [`utf8_error`]: FromUtf8Error::utf8_error
376///
377/// # Examples
378///
379/// ```
380/// // some invalid bytes, in a vector
381/// let bytes = vec![0, 159];
382///
383/// let value = String::from_utf8(bytes);
384///
385/// assert!(value.is_err());
386/// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
387/// ```
388#[stable(feature = "rust1", since = "1.0.0")]
389#[cfg_attr(not(no_global_oom_handling), derive(Clone))]
390#[derive(Debug, PartialEq, Eq)]
391pub struct FromUtf8Error {
392 bytes: Vec<u8>,
393 error: Utf8Error,
394}
395
396/// A possible error value when converting a `String` from a UTF-16 byte slice.
397///
398/// This type is the error type for the [`from_utf16`] method on [`String`].
399///
400/// [`from_utf16`]: String::from_utf16
401///
402/// # Examples
403///
404/// ```
405/// // 𝄞mu<invalid>ic
406/// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
407/// 0xD800, 0x0069, 0x0063];
408///
409/// assert!(String::from_utf16(v).is_err());
410/// ```
411#[stable(feature = "rust1", since = "1.0.0")]
412#[derive(Debug)]
413pub struct FromUtf16Error {
414 kind: FromUtf16ErrorKind,
415}
416
417#[cfg_attr(no_global_oom_handling, expect(dead_code))]
418#[derive(Clone, PartialEq, Eq, Debug)]
419enum FromUtf16ErrorKind {
420 LoneSurrogate,
421 OddBytes,
422}
423
424impl String {
425 /// Creates a new empty `String`.
426 ///
427 /// Given that the `String` is empty, this will not allocate any initial
428 /// buffer. While that means that this initial operation is very
429 /// inexpensive, it may cause excessive allocation later when you add
430 /// data. If you have an idea of how much data the `String` will hold,
431 /// consider the [`with_capacity`] method to prevent excessive
432 /// re-allocation.
433 ///
434 /// [`with_capacity`]: String::with_capacity
435 ///
436 /// # Examples
437 ///
438 /// ```
439 /// let s = String::new();
440 /// ```
441 #[inline]
442 #[rustc_const_stable(feature = "const_string_new", since = "1.39.0")]
443 #[rustc_diagnostic_item = "string_new"]
444 #[stable(feature = "rust1", since = "1.0.0")]
445 #[must_use]
446 pub const fn new() -> String {
447 String { vec: Vec::new() }
448 }
449
450 /// Creates a new empty `String` with at least the specified capacity.
451 ///
452 /// `String`s have an internal buffer to hold their data. The capacity is
453 /// the length of that buffer, and can be queried with the [`capacity`]
454 /// method. This method creates an empty `String`, but one with an initial
455 /// buffer that can hold at least `capacity` bytes. This is useful when you
456 /// may be appending a bunch of data to the `String`, reducing the number of
457 /// reallocations it needs to do.
458 ///
459 /// [`capacity`]: String::capacity
460 ///
461 /// If the given capacity is `0`, no allocation will occur, and this method
462 /// is identical to the [`new`] method.
463 ///
464 /// [`new`]: String::new
465 ///
466 /// # Panics
467 ///
468 /// Panics if the capacity exceeds `isize::MAX` _bytes_.
469 ///
470 /// # Examples
471 ///
472 /// ```
473 /// let mut s = String::with_capacity(10);
474 ///
475 /// // The String contains no chars, even though it has capacity for more
476 /// assert_eq!(s.len(), 0);
477 ///
478 /// // These are all done without reallocating...
479 /// let cap = s.capacity();
480 /// for _ in 0..10 {
481 /// s.push('a');
482 /// }
483 ///
484 /// assert_eq!(s.capacity(), cap);
485 ///
486 /// // ...but this may make the string reallocate
487 /// s.push('a');
488 /// ```
489 #[cfg(not(no_global_oom_handling))]
490 #[inline]
491 #[stable(feature = "rust1", since = "1.0.0")]
492 #[must_use]
493 pub fn with_capacity(capacity: usize) -> String {
494 String { vec: Vec::with_capacity(capacity) }
495 }
496
497 /// Creates a new empty `String` with at least the specified capacity.
498 ///
499 /// # Errors
500 ///
501 /// Returns [`Err`] if the capacity exceeds `isize::MAX` bytes,
502 /// or if the memory allocator reports failure.
503 ///
504 #[inline]
505 #[unstable(feature = "try_with_capacity", issue = "91913")]
506 pub fn try_with_capacity(capacity: usize) -> Result<String, TryReserveError> {
507 Ok(String { vec: Vec::try_with_capacity(capacity)? })
508 }
509
510 /// Converts a vector of bytes to a `String`.
511 ///
512 /// A string ([`String`]) is made of bytes ([`u8`]), and a vector of bytes
513 /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
514 /// two. Not all byte slices are valid `String`s, however: `String`
515 /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
516 /// the bytes are valid UTF-8, and then does the conversion.
517 ///
518 /// If you are sure that the byte slice is valid UTF-8, and you don't want
519 /// to incur the overhead of the validity check, there is an unsafe version
520 /// of this function, [`from_utf8_unchecked`], which has the same behavior
521 /// but skips the check.
522 ///
523 /// This method will take care to not copy the vector, for efficiency's
524 /// sake.
525 ///
526 /// If you need a [`&str`] instead of a `String`, consider
527 /// [`str::from_utf8`].
528 ///
529 /// The inverse of this method is [`into_bytes`].
530 ///
531 /// # Errors
532 ///
533 /// Returns [`Err`] if the slice is not UTF-8 with a description as to why the
534 /// provided bytes are not UTF-8. The vector you moved in is also included.
535 ///
536 /// # Examples
537 ///
538 /// Basic usage:
539 ///
540 /// ```
541 /// // some bytes, in a vector
542 /// let sparkle_heart = vec![240, 159, 146, 150];
543 ///
544 /// // We know these bytes are valid, so we'll use `unwrap()`.
545 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
546 ///
547 /// assert_eq!("💖", sparkle_heart);
548 /// ```
549 ///
550 /// Incorrect bytes:
551 ///
552 /// ```
553 /// // some invalid bytes, in a vector
554 /// let sparkle_heart = vec![0, 159, 146, 150];
555 ///
556 /// assert!(String::from_utf8(sparkle_heart).is_err());
557 /// ```
558 ///
559 /// See the docs for [`FromUtf8Error`] for more details on what you can do
560 /// with this error.
561 ///
562 /// [`from_utf8_unchecked`]: String::from_utf8_unchecked
563 /// [`Vec<u8>`]: crate::vec::Vec "Vec"
564 /// [`&str`]: prim@str "&str"
565 /// [`into_bytes`]: String::into_bytes
566 #[inline]
567 #[stable(feature = "rust1", since = "1.0.0")]
568 #[rustc_diagnostic_item = "string_from_utf8"]
569 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
570 match str::from_utf8(&vec) {
571 Ok(..) => Ok(String { vec }),
572 Err(e) => Err(FromUtf8Error { bytes: vec, error: e }),
573 }
574 }
575
576 /// Converts a slice of bytes to a string, including invalid characters.
577 ///
578 /// Strings are made of bytes ([`u8`]), and a slice of bytes
579 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
580 /// between the two. Not all byte slices are valid strings, however: strings
581 /// are required to be valid UTF-8. During this conversion,
582 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
583 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD], which looks like this: �
584 ///
585 /// [byteslice]: prim@slice
586 /// [U+FFFD]: core::char::REPLACEMENT_CHARACTER
587 ///
588 /// If you are sure that the byte slice is valid UTF-8, and you don't want
589 /// to incur the overhead of the conversion, there is an unsafe version
590 /// of this function, [`from_utf8_unchecked`], which has the same behavior
591 /// but skips the checks.
592 ///
593 /// [`from_utf8_unchecked`]: String::from_utf8_unchecked
594 ///
595 /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
596 /// UTF-8, then we need to insert the replacement characters, which will
597 /// change the size of the string, and hence, require a `String`. But if
598 /// it's already valid UTF-8, we don't need a new allocation. This return
599 /// type allows us to handle both cases.
600 ///
601 /// [`Cow<'a, str>`]: crate::borrow::Cow "borrow::Cow"
602 ///
603 /// # Examples
604 ///
605 /// Basic usage:
606 ///
607 /// ```
608 /// // some bytes, in a vector
609 /// let sparkle_heart = vec![240, 159, 146, 150];
610 ///
611 /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
612 ///
613 /// assert_eq!("💖", sparkle_heart);
614 /// ```
615 ///
616 /// Incorrect bytes:
617 ///
618 /// ```
619 /// // some invalid bytes
620 /// let input = b"Hello \xF0\x90\x80World";
621 /// let output = String::from_utf8_lossy(input);
622 ///
623 /// assert_eq!("Hello �World", output);
624 /// ```
625 #[must_use]
626 #[cfg(not(no_global_oom_handling))]
627 #[stable(feature = "rust1", since = "1.0.0")]
628 pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str> {
629 let mut iter = v.utf8_chunks();
630
631 let Some(chunk) = iter.next() else {
632 return Cow::Borrowed("");
633 };
634 let first_valid = chunk.valid();
635 if chunk.invalid().is_empty() {
636 debug_assert_eq!(first_valid.len(), v.len());
637 return Cow::Borrowed(first_valid);
638 }
639
640 const REPLACEMENT: &str = "\u{FFFD}";
641
642 let mut res = String::with_capacity(v.len());
643 res.push_str(first_valid);
644 res.push_str(REPLACEMENT);
645
646 for chunk in iter {
647 res.push_str(chunk.valid());
648 if !chunk.invalid().is_empty() {
649 res.push_str(REPLACEMENT);
650 }
651 }
652
653 Cow::Owned(res)
654 }
655
656 /// Converts a [`Vec<u8>`] to a `String`, substituting invalid UTF-8
657 /// sequences with replacement characters.
658 ///
659 /// See [`from_utf8_lossy`] for more details.
660 ///
661 /// [`from_utf8_lossy`]: String::from_utf8_lossy
662 ///
663 /// Note that this function does not guarantee reuse of the original `Vec`
664 /// allocation.
665 ///
666 /// # Examples
667 ///
668 /// Basic usage:
669 ///
670 /// ```
671 /// #![feature(string_from_utf8_lossy_owned)]
672 /// // some bytes, in a vector
673 /// let sparkle_heart = vec![240, 159, 146, 150];
674 ///
675 /// let sparkle_heart = String::from_utf8_lossy_owned(sparkle_heart);
676 ///
677 /// assert_eq!(String::from("💖"), sparkle_heart);
678 /// ```
679 ///
680 /// Incorrect bytes:
681 ///
682 /// ```
683 /// #![feature(string_from_utf8_lossy_owned)]
684 /// // some invalid bytes
685 /// let input: Vec<u8> = b"Hello \xF0\x90\x80World".into();
686 /// let output = String::from_utf8_lossy_owned(input);
687 ///
688 /// assert_eq!(String::from("Hello �World"), output);
689 /// ```
690 #[must_use]
691 #[cfg(not(no_global_oom_handling))]
692 #[unstable(feature = "string_from_utf8_lossy_owned", issue = "129436")]
693 pub fn from_utf8_lossy_owned(v: Vec<u8>) -> String {
694 if let Cow::Owned(string) = String::from_utf8_lossy(&v) {
695 string
696 } else {
697 // SAFETY: `String::from_utf8_lossy`'s contract ensures that if
698 // it returns a `Cow::Borrowed`, it is a valid UTF-8 string.
699 // Otherwise, it returns a new allocation of an owned `String`, with
700 // replacement characters for invalid sequences, which is returned
701 // above.
702 unsafe { String::from_utf8_unchecked(v) }
703 }
704 }
705
706 /// Decode a native endian UTF-16–encoded vector `v` into a `String`,
707 /// returning [`Err`] if `v` contains any invalid data.
708 ///
709 /// # Examples
710 ///
711 /// ```
712 /// // 𝄞music
713 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
714 /// 0x0073, 0x0069, 0x0063];
715 /// assert_eq!(String::from("𝄞music"),
716 /// String::from_utf16(v).unwrap());
717 ///
718 /// // 𝄞mu<invalid>ic
719 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
720 /// 0xD800, 0x0069, 0x0063];
721 /// assert!(String::from_utf16(v).is_err());
722 /// ```
723 #[cfg(not(no_global_oom_handling))]
724 #[stable(feature = "rust1", since = "1.0.0")]
725 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
726 // This isn't done via collect::<Result<_, _>>() for performance reasons.
727 // FIXME: the function can be simplified again when #48994 is closed.
728 let mut ret = String::with_capacity(v.len());
729 for c in char::decode_utf16(v.iter().cloned()) {
730 let Ok(c) = c else {
731 return Err(FromUtf16Error { kind: FromUtf16ErrorKind::LoneSurrogate });
732 };
733 ret.push(c);
734 }
735 Ok(ret)
736 }
737
738 /// Decode a native endian UTF-16–encoded slice `v` into a `String`,
739 /// replacing invalid data with [the replacement character (`U+FFFD`)][U+FFFD].
740 ///
741 /// Unlike [`from_utf8_lossy`] which returns a [`Cow<'a, str>`],
742 /// `from_utf16_lossy` returns a `String` since the UTF-16 to UTF-8
743 /// conversion requires a memory allocation.
744 ///
745 /// [`from_utf8_lossy`]: String::from_utf8_lossy
746 /// [`Cow<'a, str>`]: crate::borrow::Cow "borrow::Cow"
747 /// [U+FFFD]: core::char::REPLACEMENT_CHARACTER
748 ///
749 /// # Examples
750 ///
751 /// ```
752 /// // 𝄞mus<invalid>ic<invalid>
753 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
754 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
755 /// 0xD834];
756 ///
757 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
758 /// String::from_utf16_lossy(v));
759 /// ```
760 #[cfg(not(no_global_oom_handling))]
761 #[must_use]
762 #[inline]
763 #[stable(feature = "rust1", since = "1.0.0")]
764 pub fn from_utf16_lossy(v: &[u16]) -> String {
765 char::decode_utf16(v.iter().cloned())
766 .map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER))
767 .collect()
768 }
769
770 /// Decode a UTF-16LE–encoded vector `v` into a `String`,
771 /// returning [`Err`] if `v` contains any invalid data.
772 ///
773 /// # Examples
774 ///
775 /// Basic usage:
776 ///
777 /// ```
778 /// #![feature(str_from_utf16_endian)]
779 /// // 𝄞music
780 /// let v = &[0x34, 0xD8, 0x1E, 0xDD, 0x6d, 0x00, 0x75, 0x00,
781 /// 0x73, 0x00, 0x69, 0x00, 0x63, 0x00];
782 /// assert_eq!(String::from("𝄞music"),
783 /// String::from_utf16le(v).unwrap());
784 ///
785 /// // 𝄞mu<invalid>ic
786 /// let v = &[0x34, 0xD8, 0x1E, 0xDD, 0x6d, 0x00, 0x75, 0x00,
787 /// 0x00, 0xD8, 0x69, 0x00, 0x63, 0x00];
788 /// assert!(String::from_utf16le(v).is_err());
789 /// ```
790 #[cfg(not(no_global_oom_handling))]
791 #[unstable(feature = "str_from_utf16_endian", issue = "116258")]
792 pub fn from_utf16le(v: &[u8]) -> Result<String, FromUtf16Error> {
793 let (chunks, []) = v.as_chunks::<2>() else {
794 return Err(FromUtf16Error { kind: FromUtf16ErrorKind::OddBytes });
795 };
796 match (cfg!(target_endian = "little"), unsafe { v.align_to::<u16>() }) {
797 (true, ([], v, [])) => Self::from_utf16(v),
798 _ => char::decode_utf16(chunks.iter().copied().map(u16::from_le_bytes))
799 .collect::<Result<_, _>>()
800 .map_err(|_| FromUtf16Error { kind: FromUtf16ErrorKind::LoneSurrogate }),
801 }
802 }
803
804 /// Decode a UTF-16LE–encoded slice `v` into a `String`, replacing
805 /// invalid data with [the replacement character (`U+FFFD`)][U+FFFD].
806 ///
807 /// Unlike [`from_utf8_lossy`] which returns a [`Cow<'a, str>`],
808 /// `from_utf16le_lossy` returns a `String` since the UTF-16 to UTF-8
809 /// conversion requires a memory allocation.
810 ///
811 /// [`from_utf8_lossy`]: String::from_utf8_lossy
812 /// [`Cow<'a, str>`]: crate::borrow::Cow "borrow::Cow"
813 /// [U+FFFD]: core::char::REPLACEMENT_CHARACTER
814 ///
815 /// # Examples
816 ///
817 /// Basic usage:
818 ///
819 /// ```
820 /// #![feature(str_from_utf16_endian)]
821 /// // 𝄞mus<invalid>ic<invalid>
822 /// let v = &[0x34, 0xD8, 0x1E, 0xDD, 0x6d, 0x00, 0x75, 0x00,
823 /// 0x73, 0x00, 0x1E, 0xDD, 0x69, 0x00, 0x63, 0x00,
824 /// 0x34, 0xD8];
825 ///
826 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
827 /// String::from_utf16le_lossy(v));
828 /// ```
829 #[cfg(not(no_global_oom_handling))]
830 #[unstable(feature = "str_from_utf16_endian", issue = "116258")]
831 pub fn from_utf16le_lossy(v: &[u8]) -> String {
832 match (cfg!(target_endian = "little"), unsafe { v.align_to::<u16>() }) {
833 (true, ([], v, [])) => Self::from_utf16_lossy(v),
834 (true, ([], v, [_remainder])) => Self::from_utf16_lossy(v) + "\u{FFFD}",
835 _ => {
836 let (chunks, remainder) = v.as_chunks::<2>();
837 let string = char::decode_utf16(chunks.iter().copied().map(u16::from_le_bytes))
838 .map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER))
839 .collect();
840 if remainder.is_empty() { string } else { string + "\u{FFFD}" }
841 }
842 }
843 }
844
845 /// Decode a UTF-16BE–encoded vector `v` into a `String`,
846 /// returning [`Err`] if `v` contains any invalid data.
847 ///
848 /// # Examples
849 ///
850 /// Basic usage:
851 ///
852 /// ```
853 /// #![feature(str_from_utf16_endian)]
854 /// // 𝄞music
855 /// let v = &[0xD8, 0x34, 0xDD, 0x1E, 0x00, 0x6d, 0x00, 0x75,
856 /// 0x00, 0x73, 0x00, 0x69, 0x00, 0x63];
857 /// assert_eq!(String::from("𝄞music"),
858 /// String::from_utf16be(v).unwrap());
859 ///
860 /// // 𝄞mu<invalid>ic
861 /// let v = &[0xD8, 0x34, 0xDD, 0x1E, 0x00, 0x6d, 0x00, 0x75,
862 /// 0xD8, 0x00, 0x00, 0x69, 0x00, 0x63];
863 /// assert!(String::from_utf16be(v).is_err());
864 /// ```
865 #[cfg(not(no_global_oom_handling))]
866 #[unstable(feature = "str_from_utf16_endian", issue = "116258")]
867 pub fn from_utf16be(v: &[u8]) -> Result<String, FromUtf16Error> {
868 let (chunks, []) = v.as_chunks::<2>() else {
869 return Err(FromUtf16Error { kind: FromUtf16ErrorKind::OddBytes });
870 };
871 match (cfg!(target_endian = "big"), unsafe { v.align_to::<u16>() }) {
872 (true, ([], v, [])) => Self::from_utf16(v),
873 _ => char::decode_utf16(chunks.iter().copied().map(u16::from_be_bytes))
874 .collect::<Result<_, _>>()
875 .map_err(|_| FromUtf16Error { kind: FromUtf16ErrorKind::LoneSurrogate }),
876 }
877 }
878
879 /// Decode a UTF-16BE–encoded slice `v` into a `String`, replacing
880 /// invalid data with [the replacement character (`U+FFFD`)][U+FFFD].
881 ///
882 /// Unlike [`from_utf8_lossy`] which returns a [`Cow<'a, str>`],
883 /// `from_utf16le_lossy` returns a `String` since the UTF-16 to UTF-8
884 /// conversion requires a memory allocation.
885 ///
886 /// [`from_utf8_lossy`]: String::from_utf8_lossy
887 /// [`Cow<'a, str>`]: crate::borrow::Cow "borrow::Cow"
888 /// [U+FFFD]: core::char::REPLACEMENT_CHARACTER
889 ///
890 /// # Examples
891 ///
892 /// Basic usage:
893 ///
894 /// ```
895 /// #![feature(str_from_utf16_endian)]
896 /// // 𝄞mus<invalid>ic<invalid>
897 /// let v = &[0xD8, 0x34, 0xDD, 0x1E, 0x00, 0x6d, 0x00, 0x75,
898 /// 0x00, 0x73, 0xDD, 0x1E, 0x00, 0x69, 0x00, 0x63,
899 /// 0xD8, 0x34];
900 ///
901 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
902 /// String::from_utf16be_lossy(v));
903 /// ```
904 #[cfg(not(no_global_oom_handling))]
905 #[unstable(feature = "str_from_utf16_endian", issue = "116258")]
906 pub fn from_utf16be_lossy(v: &[u8]) -> String {
907 match (cfg!(target_endian = "big"), unsafe { v.align_to::<u16>() }) {
908 (true, ([], v, [])) => Self::from_utf16_lossy(v),
909 (true, ([], v, [_remainder])) => Self::from_utf16_lossy(v) + "\u{FFFD}",
910 _ => {
911 let (chunks, remainder) = v.as_chunks::<2>();
912 let string = char::decode_utf16(chunks.iter().copied().map(u16::from_be_bytes))
913 .map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER))
914 .collect();
915 if remainder.is_empty() { string } else { string + "\u{FFFD}" }
916 }
917 }
918 }
919
920 /// Decomposes a `String` into its raw components: `(pointer, length, capacity)`.
921 ///
922 /// Returns the raw pointer to the underlying data, the length of
923 /// the string (in bytes), and the allocated capacity of the data
924 /// (in bytes). These are the same arguments in the same order as
925 /// the arguments to [`from_raw_parts`].
926 ///
927 /// After calling this function, the caller is responsible for the
928 /// memory previously managed by the `String`. The only way to do
929 /// this is to convert the raw pointer, length, and capacity back
930 /// into a `String` with the [`from_raw_parts`] function, allowing
931 /// the destructor to perform the cleanup.
932 ///
933 /// [`from_raw_parts`]: String::from_raw_parts
934 ///
935 /// # Examples
936 ///
937 /// ```
938 /// let s = String::from("hello");
939 ///
940 /// let (ptr, len, cap) = s.into_raw_parts();
941 ///
942 /// let rebuilt = unsafe { String::from_raw_parts(ptr, len, cap) };
943 /// assert_eq!(rebuilt, "hello");
944 /// ```
945 #[must_use = "losing the pointer will leak memory"]
946 #[stable(feature = "vec_into_raw_parts", since = "1.93.0")]
947 pub fn into_raw_parts(self) -> (*mut u8, usize, usize) {
948 self.vec.into_raw_parts()
949 }
950
951 /// Creates a new `String` from a pointer, a length and a capacity.
952 ///
953 /// # Safety
954 ///
955 /// This is highly unsafe, due to the number of invariants that aren't
956 /// checked:
957 ///
958 /// * all safety requirements for [`Vec::<u8>::from_raw_parts`].
959 /// * all safety requirements for [`String::from_utf8_unchecked`].
960 ///
961 /// Violating these may cause problems like corrupting the allocator's
962 /// internal data structures. For example, it is normally **not** safe to
963 /// build a `String` from a pointer to a C `char` array containing UTF-8
964 /// _unless_ you are certain that array was originally allocated by the
965 /// Rust standard library's allocator.
966 ///
967 /// The ownership of `buf` is effectively transferred to the
968 /// `String` which may then deallocate, reallocate or change the
969 /// contents of memory pointed to by the pointer at will. Ensure
970 /// that nothing else uses the pointer after calling this
971 /// function.
972 ///
973 /// # Examples
974 ///
975 /// ```
976 /// unsafe {
977 /// let s = String::from("hello");
978 ///
979 /// // Deconstruct the String into parts.
980 /// let (ptr, len, capacity) = s.into_raw_parts();
981 ///
982 /// let s = String::from_raw_parts(ptr, len, capacity);
983 ///
984 /// assert_eq!(String::from("hello"), s);
985 /// }
986 /// ```
987 #[inline]
988 #[stable(feature = "rust1", since = "1.0.0")]
989 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
990 unsafe { String { vec: Vec::from_raw_parts(buf, length, capacity) } }
991 }
992
993 /// Converts a vector of bytes to a `String` without checking that the
994 /// string contains valid UTF-8.
995 ///
996 /// See the safe version, [`from_utf8`], for more details.
997 ///
998 /// [`from_utf8`]: String::from_utf8
999 ///
1000 /// # Safety
1001 ///
1002 /// This function is unsafe because it does not check that the bytes passed
1003 /// to it are valid UTF-8. If this constraint is violated, it may cause
1004 /// memory unsafety issues with future users of the `String`, as the rest of
1005 /// the standard library assumes that `String`s are valid UTF-8.
1006 ///
1007 /// # Examples
1008 ///
1009 /// ```
1010 /// // some bytes, in a vector
1011 /// let sparkle_heart = vec![240, 159, 146, 150];
1012 ///
1013 /// let sparkle_heart = unsafe {
1014 /// String::from_utf8_unchecked(sparkle_heart)
1015 /// };
1016 ///
1017 /// assert_eq!("💖", sparkle_heart);
1018 /// ```
1019 #[inline]
1020 #[must_use]
1021 #[stable(feature = "rust1", since = "1.0.0")]
1022 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
1023 String { vec: bytes }
1024 }
1025
1026 /// Converts a `String` into a byte vector.
1027 ///
1028 /// This consumes the `String`, so we do not need to copy its contents.
1029 ///
1030 /// # Examples
1031 ///
1032 /// ```
1033 /// let s = String::from("hello");
1034 /// let bytes = s.into_bytes();
1035 ///
1036 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
1037 /// ```
1038 #[inline]
1039 #[must_use = "`self` will be dropped if the result is not used"]
1040 #[stable(feature = "rust1", since = "1.0.0")]
1041 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1042 #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
1043 pub const fn into_bytes(self) -> Vec<u8> {
1044 self.vec
1045 }
1046
1047 /// Extracts a string slice containing the entire `String`.
1048 ///
1049 /// # Examples
1050 ///
1051 /// ```
1052 /// let s = String::from("foo");
1053 ///
1054 /// assert_eq!("foo", s.as_str());
1055 /// ```
1056 #[inline]
1057 #[must_use]
1058 #[stable(feature = "string_as_str", since = "1.7.0")]
1059 #[rustc_diagnostic_item = "string_as_str"]
1060 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1061 pub const fn as_str(&self) -> &str {
1062 // SAFETY: String contents are stipulated to be valid UTF-8, invalid contents are an error
1063 // at construction.
1064 unsafe { str::from_utf8_unchecked(self.vec.as_slice()) }
1065 }
1066
1067 /// Converts a `String` into a mutable string slice.
1068 ///
1069 /// # Examples
1070 ///
1071 /// ```
1072 /// let mut s = String::from("foobar");
1073 /// let s_mut_str = s.as_mut_str();
1074 ///
1075 /// s_mut_str.make_ascii_uppercase();
1076 ///
1077 /// assert_eq!("FOOBAR", s_mut_str);
1078 /// ```
1079 #[inline]
1080 #[must_use]
1081 #[stable(feature = "string_as_str", since = "1.7.0")]
1082 #[rustc_diagnostic_item = "string_as_mut_str"]
1083 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1084 pub const fn as_mut_str(&mut self) -> &mut str {
1085 // SAFETY: String contents are stipulated to be valid UTF-8, invalid contents are an error
1086 // at construction.
1087 unsafe { str::from_utf8_unchecked_mut(self.vec.as_mut_slice()) }
1088 }
1089
1090 /// Appends a given string slice onto the end of this `String`.
1091 ///
1092 /// # Panics
1093 ///
1094 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
1095 ///
1096 /// # Examples
1097 ///
1098 /// ```
1099 /// let mut s = String::from("foo");
1100 ///
1101 /// s.push_str("bar");
1102 ///
1103 /// assert_eq!("foobar", s);
1104 /// ```
1105 #[cfg(not(no_global_oom_handling))]
1106 #[inline]
1107 #[stable(feature = "rust1", since = "1.0.0")]
1108 #[rustc_confusables("append", "push")]
1109 #[rustc_diagnostic_item = "string_push_str"]
1110 pub fn push_str(&mut self, string: &str) {
1111 self.vec.extend_from_slice(string.as_bytes())
1112 }
1113
1114 #[cfg(not(no_global_oom_handling))]
1115 #[inline]
1116 fn push_str_slice(&mut self, slice: &[&str]) {
1117 // use saturating arithmetic to ensure that in the case of an overflow, reserve() throws OOM
1118 let additional: Saturating<usize> = slice.iter().map(|x| Saturating(x.len())).sum();
1119 self.reserve(additional.0);
1120 let (ptr, len, cap) = core::mem::take(self).into_raw_parts();
1121 unsafe {
1122 let mut dst = ptr.add(len);
1123 for new in slice {
1124 core::ptr::copy_nonoverlapping(new.as_ptr(), dst, new.len());
1125 dst = dst.add(new.len());
1126 }
1127 *self = String::from_raw_parts(ptr, len + additional.0, cap);
1128 }
1129 }
1130
1131 /// Copies elements from `src` range to the end of the string.
1132 ///
1133 /// # Panics
1134 ///
1135 /// Panics if the range has `start_bound > end_bound`, if the range is
1136 /// bounded on either end and does not lie on a [`char`] boundary, or if the
1137 /// new capacity exceeds `isize::MAX` bytes.
1138 ///
1139 /// # Examples
1140 ///
1141 /// ```
1142 /// let mut string = String::from("abcde");
1143 ///
1144 /// string.extend_from_within(2..);
1145 /// assert_eq!(string, "abcdecde");
1146 ///
1147 /// string.extend_from_within(..2);
1148 /// assert_eq!(string, "abcdecdeab");
1149 ///
1150 /// string.extend_from_within(4..8);
1151 /// assert_eq!(string, "abcdecdeabecde");
1152 /// ```
1153 #[cfg(not(no_global_oom_handling))]
1154 #[stable(feature = "string_extend_from_within", since = "1.87.0")]
1155 #[track_caller]
1156 pub fn extend_from_within<R>(&mut self, src: R)
1157 where
1158 R: RangeBounds<usize>,
1159 {
1160 let src @ Range { start, end } = slice::range(src, ..self.len());
1161
1162 assert!(self.is_char_boundary(start));
1163 assert!(self.is_char_boundary(end));
1164
1165 self.vec.extend_from_within(src);
1166 }
1167
1168 /// Returns this `String`'s capacity, in bytes.
1169 ///
1170 /// # Examples
1171 ///
1172 /// ```
1173 /// let s = String::with_capacity(10);
1174 ///
1175 /// assert!(s.capacity() >= 10);
1176 /// ```
1177 #[inline]
1178 #[must_use]
1179 #[stable(feature = "rust1", since = "1.0.0")]
1180 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1181 pub const fn capacity(&self) -> usize {
1182 self.vec.capacity()
1183 }
1184
1185 /// Reserves capacity for at least `additional` bytes more than the
1186 /// current length. The allocator may reserve more space to speculatively
1187 /// avoid frequent allocations. After calling `reserve`,
1188 /// capacity will be greater than or equal to `self.len() + additional`.
1189 /// Does nothing if capacity is already sufficient.
1190 ///
1191 /// # Panics
1192 ///
1193 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
1194 ///
1195 /// # Examples
1196 ///
1197 /// Basic usage:
1198 ///
1199 /// ```
1200 /// let mut s = String::new();
1201 ///
1202 /// s.reserve(10);
1203 ///
1204 /// assert!(s.capacity() >= 10);
1205 /// ```
1206 ///
1207 /// This might not actually increase the capacity:
1208 ///
1209 /// ```
1210 /// let mut s = String::with_capacity(10);
1211 /// s.push('a');
1212 /// s.push('b');
1213 ///
1214 /// // s now has a length of 2 and a capacity of at least 10
1215 /// let capacity = s.capacity();
1216 /// assert_eq!(2, s.len());
1217 /// assert!(capacity >= 10);
1218 ///
1219 /// // Since we already have at least an extra 8 capacity, calling this...
1220 /// s.reserve(8);
1221 ///
1222 /// // ... doesn't actually increase.
1223 /// assert_eq!(capacity, s.capacity());
1224 /// ```
1225 #[cfg(not(no_global_oom_handling))]
1226 #[inline]
1227 #[stable(feature = "rust1", since = "1.0.0")]
1228 pub fn reserve(&mut self, additional: usize) {
1229 self.vec.reserve(additional)
1230 }
1231
1232 /// Reserves the minimum capacity for at least `additional` bytes more than
1233 /// the current length. Unlike [`reserve`], this will not
1234 /// deliberately over-allocate to speculatively avoid frequent allocations.
1235 /// After calling `reserve_exact`, capacity will be greater than or equal to
1236 /// `self.len() + additional`. Does nothing if the capacity is already
1237 /// sufficient.
1238 ///
1239 /// [`reserve`]: String::reserve
1240 ///
1241 /// # Panics
1242 ///
1243 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
1244 ///
1245 /// # Examples
1246 ///
1247 /// Basic usage:
1248 ///
1249 /// ```
1250 /// let mut s = String::new();
1251 ///
1252 /// s.reserve_exact(10);
1253 ///
1254 /// assert!(s.capacity() >= 10);
1255 /// ```
1256 ///
1257 /// This might not actually increase the capacity:
1258 ///
1259 /// ```
1260 /// let mut s = String::with_capacity(10);
1261 /// s.push('a');
1262 /// s.push('b');
1263 ///
1264 /// // s now has a length of 2 and a capacity of at least 10
1265 /// let capacity = s.capacity();
1266 /// assert_eq!(2, s.len());
1267 /// assert!(capacity >= 10);
1268 ///
1269 /// // Since we already have at least an extra 8 capacity, calling this...
1270 /// s.reserve_exact(8);
1271 ///
1272 /// // ... doesn't actually increase.
1273 /// assert_eq!(capacity, s.capacity());
1274 /// ```
1275 #[cfg(not(no_global_oom_handling))]
1276 #[inline]
1277 #[stable(feature = "rust1", since = "1.0.0")]
1278 pub fn reserve_exact(&mut self, additional: usize) {
1279 self.vec.reserve_exact(additional)
1280 }
1281
1282 /// Tries to reserve capacity for at least `additional` bytes more than the
1283 /// current length. The allocator may reserve more space to speculatively
1284 /// avoid frequent allocations. After calling `try_reserve`, capacity will be
1285 /// greater than or equal to `self.len() + additional` if it returns
1286 /// `Ok(())`. Does nothing if capacity is already sufficient. This method
1287 /// preserves the contents even if an error occurs.
1288 ///
1289 /// # Errors
1290 ///
1291 /// If the capacity overflows, or the allocator reports a failure, then an error
1292 /// is returned.
1293 ///
1294 /// # Examples
1295 ///
1296 /// ```
1297 /// use std::collections::TryReserveError;
1298 ///
1299 /// fn process_data(data: &