1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A UTF-8 encoded, growable string.
13 //! This module contains the [`String`] type, a trait for converting
14 //! [`ToString`]s, and several error types that may result from working with
17 //! [`ToString`]: trait.ToString.html
21 //! There are multiple ways to create a new [`String`] from a string literal:
24 //! let s = "Hello".to_string();
26 //! let s = String::from("world");
27 //! let s: String = "also this".into();
30 //! You can create a new [`String`] from an existing one by concatenating with
33 //! [`String`]: struct.String.html
36 //! let s = "Hello".to_string();
38 //! let message = s + " world!";
41 //! If you have a vector of valid UTF-8 bytes, you can make a `String` out of
42 //! it. You can do the reverse too.
45 //! let sparkle_heart = vec![240, 159, 146, 150];
47 //! // We know these bytes are valid, so we'll use `unwrap()`.
48 //! let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
50 //! assert_eq!("💖", sparkle_heart);
52 //! let bytes = sparkle_heart.into_bytes();
54 //! assert_eq!(bytes, [240, 159, 146, 150]);
57 #![stable(feature = "rust1", since = "1.0.0")]
61 use core::iter::{FromIterator, FusedIterator};
62 use core::ops::{self, Add, AddAssign, Index, IndexMut};
64 use core::str::pattern::Pattern;
65 use std_unicode::lossy;
66 use std_unicode::char::{decode_utf16, REPLACEMENT_CHARACTER};
68 use borrow::{Cow, ToOwned};
69 use range::RangeArgument;
70 use Bound::{Excluded, Included, Unbounded};
71 use str::{self, from_boxed_utf8_unchecked, FromStr, Utf8Error, Chars};
75 /// A UTF-8 encoded, growable string.
77 /// The `String` type is the most common string type that has ownership over the
78 /// contents of the string. It has a close relationship with its borrowed
79 /// counterpart, the primitive [`str`].
81 /// [`str`]: ../../std/primitive.str.html
85 /// You can create a `String` from a literal string with `String::from`:
88 /// let hello = String::from("Hello, world!");
91 /// You can append a [`char`] to a `String` with the [`push`] method, and
92 /// append a [`&str`] with the [`push_str`] method:
95 /// let mut hello = String::from("Hello, ");
98 /// hello.push_str("orld!");
101 /// [`char`]: ../../std/primitive.char.html
102 /// [`push`]: #method.push
103 /// [`push_str`]: #method.push_str
105 /// If you have a vector of UTF-8 bytes, you can create a `String` from it with
106 /// the [`from_utf8`] method:
109 /// // some bytes, in a vector
110 /// let sparkle_heart = vec![240, 159, 146, 150];
112 /// // We know these bytes are valid, so we'll use `unwrap()`.
113 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
115 /// assert_eq!("💖", sparkle_heart);
118 /// [`from_utf8`]: #method.from_utf8
122 /// `String`s are always valid UTF-8. This has a few implications, the first of
123 /// which is that if you need a non-UTF-8 string, consider [`OsString`]. It is
124 /// similar, but without the UTF-8 constraint. The second implication is that
125 /// you cannot index into a `String`:
130 /// println!("The first letter of s is {}", s[0]); // ERROR!!!
133 /// [`OsString`]: ../../std/ffi/struct.OsString.html
135 /// Indexing is intended to be a constant-time operation, but UTF-8 encoding
136 /// does not allow us to do this. Furthermore, it's not clear what sort of
137 /// thing the index should return: a byte, a codepoint, or a grapheme cluster.
138 /// The [`bytes`] and [`chars`] methods return iterators over the first
139 /// two, respectively.
141 /// [`bytes`]: #method.bytes
142 /// [`chars`]: #method.chars
146 /// `String`s implement [`Deref`]`<Target=str>`, and so inherit all of [`str`]'s
147 /// methods. In addition, this means that you can pass a `String` to any
148 /// function which takes a [`&str`] by using an ampersand (`&`):
151 /// fn takes_str(s: &str) { }
153 /// let s = String::from("Hello");
158 /// [`&str`]: ../../std/primitive.str.html
159 /// [`Deref`]: ../../std/ops/trait.Deref.html
161 /// This will create a [`&str`] from the `String` and pass it in. This
162 /// conversion is very inexpensive, and so generally, functions will accept
163 /// [`&str`]s as arguments unless they need a `String` for some specific reason.
168 /// A `String` is made up of three components: a pointer to some bytes, a
169 /// length, and a capacity. The pointer points to an internal buffer `String`
170 /// uses to store its data. The length is the number of bytes currently stored
171 /// in the buffer, and the capacity is the size of the buffer in bytes. As such,
172 /// the length will always be less than or equal to the capacity.
174 /// This buffer is always stored on the heap.
176 /// You can look at these with the [`as_ptr`], [`len`], and [`capacity`]
182 /// let story = String::from("Once upon a time...");
184 /// let ptr = story.as_ptr();
185 /// let len = story.len();
186 /// let capacity = story.capacity();
188 /// // story has nineteen bytes
189 /// assert_eq!(19, len);
191 /// // Now that we have our parts, we throw the story away.
192 /// mem::forget(story);
194 /// // We can re-build a String out of ptr, len, and capacity. This is all
195 /// // unsafe because we are responsible for making sure the components are
197 /// let s = unsafe { String::from_raw_parts(ptr as *mut _, len, capacity) } ;
199 /// assert_eq!(String::from("Once upon a time..."), s);
202 /// [`as_ptr`]: #method.as_ptr
203 /// [`len`]: #method.len
204 /// [`capacity`]: #method.capacity
206 /// If a `String` has enough capacity, adding elements to it will not
207 /// re-allocate. For example, consider this program:
210 /// let mut s = String::new();
212 /// println!("{}", s.capacity());
215 /// s.push_str("hello");
216 /// println!("{}", s.capacity());
220 /// This will output the following:
231 /// At first, we have no memory allocated at all, but as we append to the
232 /// string, it increases its capacity appropriately. If we instead use the
233 /// [`with_capacity`] method to allocate the correct capacity initially:
236 /// let mut s = String::with_capacity(25);
238 /// println!("{}", s.capacity());
241 /// s.push_str("hello");
242 /// println!("{}", s.capacity());
246 /// [`with_capacity`]: #method.with_capacity
248 /// We end up with a different output:
259 /// Here, there's no need to allocate more memory inside the loop.
260 #[derive(PartialOrd, Eq, Ord)]
261 #[stable(feature = "rust1", since = "1.0.0")]
266 /// A possible error value when converting a `String` from a UTF-8 byte vector.
268 /// This type is the error type for the [`from_utf8`] method on [`String`]. It
269 /// is designed in such a way to carefully avoid reallocations: the
270 /// [`into_bytes`] method will give back the byte vector that was used in the
271 /// conversion attempt.
273 /// [`from_utf8`]: struct.String.html#method.from_utf8
274 /// [`String`]: struct.String.html
275 /// [`into_bytes`]: struct.FromUtf8Error.html#method.into_bytes
277 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
278 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
279 /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
280 /// through the [`utf8_error`] method.
282 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
283 /// [`std::str`]: ../../std/str/index.html
284 /// [`u8`]: ../../std/primitive.u8.html
285 /// [`&str`]: ../../std/primitive.str.html
286 /// [`utf8_error`]: #method.utf8_error
293 /// // some invalid bytes, in a vector
294 /// let bytes = vec![0, 159];
296 /// let value = String::from_utf8(bytes);
298 /// assert!(value.is_err());
299 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
301 #[stable(feature = "rust1", since = "1.0.0")]
303 pub struct FromUtf8Error {
308 /// A possible error value when converting a `String` from a UTF-16 byte slice.
310 /// This type is the error type for the [`from_utf16`] method on [`String`].
312 /// [`from_utf16`]: struct.String.html#method.from_utf16
313 /// [`String`]: struct.String.html
320 /// // 𝄞mu<invalid>ic
321 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
322 /// 0xD800, 0x0069, 0x0063];
324 /// assert!(String::from_utf16(v).is_err());
326 #[stable(feature = "rust1", since = "1.0.0")]
328 pub struct FromUtf16Error(());
331 /// Creates a new empty `String`.
333 /// Given that the `String` is empty, this will not allocate any initial
334 /// buffer. While that means that this initial operation is very
335 /// inexpensive, but may cause excessive allocation later, when you add
336 /// data. If you have an idea of how much data the `String` will hold,
337 /// consider the [`with_capacity`] method to prevent excessive
340 /// [`with_capacity`]: #method.with_capacity
347 /// let s = String::new();
350 #[stable(feature = "rust1", since = "1.0.0")]
351 pub fn new() -> String {
352 String { vec: Vec::new() }
355 /// Creates a new empty `String` with a particular capacity.
357 /// `String`s have an internal buffer to hold their data. The capacity is
358 /// the length of that buffer, and can be queried with the [`capacity`]
359 /// method. This method creates an empty `String`, but one with an initial
360 /// buffer that can hold `capacity` bytes. This is useful when you may be
361 /// appending a bunch of data to the `String`, reducing the number of
362 /// reallocations it needs to do.
364 /// [`capacity`]: #method.capacity
366 /// If the given capacity is `0`, no allocation will occur, and this method
367 /// is identical to the [`new`] method.
369 /// [`new`]: #method.new
376 /// let mut s = String::with_capacity(10);
378 /// // The String contains no chars, even though it has capacity for more
379 /// assert_eq!(s.len(), 0);
381 /// // These are all done without reallocating...
382 /// let cap = s.capacity();
387 /// assert_eq!(s.capacity(), cap);
389 /// // ...but this may make the vector reallocate
393 #[stable(feature = "rust1", since = "1.0.0")]
394 pub fn with_capacity(capacity: usize) -> String {
395 String { vec: Vec::with_capacity(capacity) }
398 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
399 // required for this method definition, is not available. Since we don't
400 // require this method for testing purposes, I'll just stub it
401 // NB see the slice::hack module in slice.rs for more information
404 pub fn from_str(_: &str) -> String {
405 panic!("not available with cfg(test)");
408 /// Converts a vector of bytes to a `String`.
410 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a vector of bytes
411 /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
412 /// two. Not all byte slices are valid `String`s, however: `String`
413 /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
414 /// the bytes are valid UTF-8, and then does the conversion.
416 /// [`&str`]: ../../std/primitive.str.html
417 /// [`u8`]: ../../std/primitive.u8.html
418 /// [`Vec<u8>`]: ../../std/vec/struct.Vec.html
420 /// If you are sure that the byte slice is valid UTF-8, and you don't want
421 /// to incur the overhead of the validity check, there is an unsafe version
422 /// of this function, [`from_utf8_unchecked`], which has the same behavior
423 /// but skips the check.
425 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
427 /// This method will take care to not copy the vector, for efficiency's
430 /// If you need a `&str` instead of a `String`, consider
431 /// [`str::from_utf8`].
433 /// [`str::from_utf8`]: ../../std/str/fn.from_utf8.html
435 /// The inverse of this method is [`as_bytes`].
437 /// [`as_bytes`]: #method.as_bytes
441 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
442 /// provided bytes are not UTF-8. The vector you moved in is also included.
449 /// // some bytes, in a vector
450 /// let sparkle_heart = vec![240, 159, 146, 150];
452 /// // We know these bytes are valid, so we'll use `unwrap()`.
453 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
455 /// assert_eq!("💖", sparkle_heart);
461 /// // some invalid bytes, in a vector
462 /// let sparkle_heart = vec![0, 159, 146, 150];
464 /// assert!(String::from_utf8(sparkle_heart).is_err());
467 /// See the docs for [`FromUtf8Error`] for more details on what you can do
470 /// [`FromUtf8Error`]: struct.FromUtf8Error.html
472 #[stable(feature = "rust1", since = "1.0.0")]
473 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
474 match str::from_utf8(&vec) {
475 Ok(..) => Ok(String { vec: vec }),
485 /// Converts a slice of bytes to a string, including invalid characters.
487 /// Strings are made of bytes ([`u8`]), and a slice of bytes
488 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
489 /// between the two. Not all byte slices are valid strings, however: strings
490 /// are required to be valid UTF-8. During this conversion,
491 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
492 /// `U+FFFD REPLACEMENT CHARACTER`, which looks like this: �
494 /// [`u8`]: ../../std/primitive.u8.html
495 /// [byteslice]: ../../std/primitive.slice.html
497 /// If you are sure that the byte slice is valid UTF-8, and you don't want
498 /// to incur the overhead of the conversion, there is an unsafe version
499 /// of this function, [`from_utf8_unchecked`], which has the same behavior
500 /// but skips the checks.
502 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
504 /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
505 /// UTF-8, then we need to insert the replacement characters, which will
506 /// change the size of the string, and hence, require a `String`. But if
507 /// it's already valid UTF-8, we don't need a new allocation. This return
508 /// type allows us to handle both cases.
510 /// [`Cow<'a, str>`]: ../../std/borrow/enum.Cow.html
517 /// // some bytes, in a vector
518 /// let sparkle_heart = vec![240, 159, 146, 150];
520 /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
522 /// assert_eq!("💖", sparkle_heart);
528 /// // some invalid bytes
529 /// let input = b"Hello \xF0\x90\x80World";
530 /// let output = String::from_utf8_lossy(input);
532 /// assert_eq!("Hello �World", output);
534 #[stable(feature = "rust1", since = "1.0.0")]
535 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
536 let mut iter = lossy::Utf8Lossy::from_bytes(v).chunks();
538 let (first_valid, first_broken) = if let Some(chunk) = iter.next() {
539 let lossy::Utf8LossyChunk { valid, broken } = chunk;
540 if valid.len() == v.len() {
541 debug_assert!(broken.is_empty());
542 return Cow::Borrowed(valid);
546 return Cow::Borrowed("");
549 const REPLACEMENT: &'static str = "\u{FFFD}";
551 let mut res = String::with_capacity(v.len());
552 res.push_str(first_valid);
553 if !first_broken.is_empty() {
554 res.push_str(REPLACEMENT);
557 for lossy::Utf8LossyChunk { valid, broken } in iter {
559 if !broken.is_empty() {
560 res.push_str(REPLACEMENT);
567 /// Decode a UTF-16 encoded vector `v` into a `String`, returning `Err`
568 /// if `v` contains any invalid data.
576 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
577 /// 0x0073, 0x0069, 0x0063];
578 /// assert_eq!(String::from("𝄞music"),
579 /// String::from_utf16(v).unwrap());
581 /// // 𝄞mu<invalid>ic
582 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
583 /// 0xD800, 0x0069, 0x0063];
584 /// assert!(String::from_utf16(v).is_err());
586 #[stable(feature = "rust1", since = "1.0.0")]
587 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
588 decode_utf16(v.iter().cloned()).collect::<Result<_, _>>().map_err(|_| FromUtf16Error(()))
591 /// Decode a UTF-16 encoded vector `v` into a string, replacing
592 /// invalid data with the replacement character (U+FFFD).
599 /// // 𝄞mus<invalid>ic<invalid>
600 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
601 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
604 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
605 /// String::from_utf16_lossy(v));
608 #[stable(feature = "rust1", since = "1.0.0")]
609 pub fn from_utf16_lossy(v: &[u16]) -> String {
610 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
613 /// Creates a new `String` from a length, capacity, and pointer.
617 /// This is highly unsafe, due to the number of invariants that aren't
620 /// * The memory at `ptr` needs to have been previously allocated by the
621 /// same allocator the standard library uses.
622 /// * `length` needs to be less than or equal to `capacity`.
623 /// * `capacity` needs to be the correct value.
625 /// Violating these may cause problems like corrupting the allocator's
626 /// internal datastructures.
628 /// The ownership of `ptr` is effectively transferred to the
629 /// `String` which may then deallocate, reallocate or change the
630 /// contents of memory pointed to by the pointer at will. Ensure
631 /// that nothing else uses the pointer after calling this
642 /// let s = String::from("hello");
643 /// let ptr = s.as_ptr();
644 /// let len = s.len();
645 /// let capacity = s.capacity();
649 /// let s = String::from_raw_parts(ptr as *mut _, len, capacity);
651 /// assert_eq!(String::from("hello"), s);
655 #[stable(feature = "rust1", since = "1.0.0")]
656 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
657 String { vec: Vec::from_raw_parts(buf, length, capacity) }
660 /// Converts a vector of bytes to a `String` without checking that the
661 /// string contains valid UTF-8.
663 /// See the safe version, [`from_utf8`], for more details.
665 /// [`from_utf8`]: struct.String.html#method.from_utf8
669 /// This function is unsafe because it does not check that the bytes passed
670 /// to it are valid UTF-8. If this constraint is violated, it may cause
671 /// memory unsafety issues with future users of the `String`, as the rest of
672 /// the standard library assumes that `String`s are valid UTF-8.
679 /// // some bytes, in a vector
680 /// let sparkle_heart = vec![240, 159, 146, 150];
682 /// let sparkle_heart = unsafe {
683 /// String::from_utf8_unchecked(sparkle_heart)
686 /// assert_eq!("💖", sparkle_heart);
689 #[stable(feature = "rust1", since = "1.0.0")]
690 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
691 String { vec: bytes }
694 /// Converts a `String` into a byte vector.
696 /// This consumes the `String`, so we do not need to copy its contents.
703 /// let s = String::from("hello");
704 /// let bytes = s.into_bytes();
706 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
709 #[stable(feature = "rust1", since = "1.0.0")]
710 pub fn into_bytes(self) -> Vec<u8> {
714 /// Extracts a string slice containing the entire string.
716 #[stable(feature = "string_as_str", since = "1.7.0")]
717 pub fn as_str(&self) -> &str {
721 /// Extracts a string slice containing the entire string.
723 #[stable(feature = "string_as_str", since = "1.7.0")]
724 pub fn as_mut_str(&mut self) -> &mut str {
728 /// Appends a given string slice onto the end of this `String`.
735 /// let mut s = String::from("foo");
737 /// s.push_str("bar");
739 /// assert_eq!("foobar", s);
742 #[stable(feature = "rust1", since = "1.0.0")]
743 pub fn push_str(&mut self, string: &str) {
744 self.vec.extend_from_slice(string.as_bytes())
747 /// Returns this `String`'s capacity, in bytes.
754 /// let s = String::with_capacity(10);
756 /// assert!(s.capacity() >= 10);
759 #[stable(feature = "rust1", since = "1.0.0")]
760 pub fn capacity(&self) -> usize {
764 /// Ensures that this `String`'s capacity is at least `additional` bytes
765 /// larger than its length.
767 /// The capacity may be increased by more than `additional` bytes if it
768 /// chooses, to prevent frequent reallocations.
770 /// If you do not want this "at least" behavior, see the [`reserve_exact`]
773 /// [`reserve_exact`]: #method.reserve_exact
777 /// Panics if the new capacity overflows `usize`.
784 /// let mut s = String::new();
788 /// assert!(s.capacity() >= 10);
791 /// This may not actually increase the capacity:
794 /// let mut s = String::with_capacity(10);
798 /// // s now has a length of 2 and a capacity of 10
799 /// assert_eq!(2, s.len());
800 /// assert_eq!(10, s.capacity());
802 /// // Since we already have an extra 8 capacity, calling this...
805 /// // ... doesn't actually increase.
806 /// assert_eq!(10, s.capacity());
809 #[stable(feature = "rust1", since = "1.0.0")]
810 pub fn reserve(&mut self, additional: usize) {
811 self.vec.reserve(additional)
814 /// Ensures that this `String`'s capacity is `additional` bytes
815 /// larger than its length.
817 /// Consider using the [`reserve`] method unless you absolutely know
818 /// better than the allocator.
820 /// [`reserve`]: #method.reserve
824 /// Panics if the new capacity overflows `usize`.
831 /// let mut s = String::new();
833 /// s.reserve_exact(10);
835 /// assert!(s.capacity() >= 10);
838 /// This may not actually increase the capacity:
841 /// let mut s = String::with_capacity(10);
845 /// // s now has a length of 2 and a capacity of 10
846 /// assert_eq!(2, s.len());
847 /// assert_eq!(10, s.capacity());
849 /// // Since we already have an extra 8 capacity, calling this...
850 /// s.reserve_exact(8);
852 /// // ... doesn't actually increase.
853 /// assert_eq!(10, s.capacity());
856 #[stable(feature = "rust1", since = "1.0.0")]
857 pub fn reserve_exact(&mut self, additional: usize) {
858 self.vec.reserve_exact(additional)
861 /// Shrinks the capacity of this `String` to match its length.
868 /// let mut s = String::from("foo");
871 /// assert!(s.capacity() >= 100);
873 /// s.shrink_to_fit();
874 /// assert_eq!(3, s.capacity());
877 #[stable(feature = "rust1", since = "1.0.0")]
878 pub fn shrink_to_fit(&mut self) {
879 self.vec.shrink_to_fit()
882 /// Appends the given `char` to the end of this `String`.
889 /// let mut s = String::from("abc");
895 /// assert_eq!("abc123", s);
898 #[stable(feature = "rust1", since = "1.0.0")]
899 pub fn push(&mut self, ch: char) {
900 match ch.len_utf8() {
901 1 => self.vec.push(ch as u8),
902 _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
906 /// Returns a byte slice of this `String`'s contents.
908 /// The inverse of this method is [`from_utf8`].
910 /// [`from_utf8`]: #method.from_utf8
917 /// let s = String::from("hello");
919 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
922 #[stable(feature = "rust1", since = "1.0.0")]
923 pub fn as_bytes(&self) -> &[u8] {
927 /// Shortens this `String` to the specified length.
929 /// If `new_len` is greater than the string's current length, this has no
932 /// Note that this method has no effect on the allocated capacity
937 /// Panics if `new_len` does not lie on a [`char`] boundary.
939 /// [`char`]: ../../std/primitive.char.html
946 /// let mut s = String::from("hello");
950 /// assert_eq!("he", s);
953 #[stable(feature = "rust1", since = "1.0.0")]
954 pub fn truncate(&mut self, new_len: usize) {
955 if new_len <= self.len() {
956 assert!(self.is_char_boundary(new_len));
957 self.vec.truncate(new_len)
961 /// Removes the last character from the string buffer and returns it.
963 /// Returns `None` if this `String` is empty.
970 /// let mut s = String::from("foo");
972 /// assert_eq!(s.pop(), Some('o'));
973 /// assert_eq!(s.pop(), Some('o'));
974 /// assert_eq!(s.pop(), Some('f'));
976 /// assert_eq!(s.pop(), None);
979 #[stable(feature = "rust1", since = "1.0.0")]
980 pub fn pop(&mut self) -> Option<char> {
981 let ch = match self.chars().rev().next() {
985 let newlen = self.len() - ch.len_utf8();
987 self.vec.set_len(newlen);
992 /// Removes a `char` from this `String` at a byte position and returns it.
994 /// This is an `O(n)` operation, as it requires copying every element in the
999 /// Panics if `idx` is larger than or equal to the `String`'s length,
1000 /// or if it does not lie on a [`char`] boundary.
1002 /// [`char`]: ../../std/primitive.char.html
1009 /// let mut s = String::from("foo");
1011 /// assert_eq!(s.remove(0), 'f');
1012 /// assert_eq!(s.remove(1), 'o');
1013 /// assert_eq!(s.remove(0), 'o');
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 pub fn remove(&mut self, idx: usize) -> char {
1018 let ch = match self[idx..].chars().next() {
1020 None => panic!("cannot remove a char from the end of a string"),
1023 let next = idx + ch.len_utf8();
1024 let len = self.len();
1026 ptr::copy(self.vec.as_ptr().offset(next as isize),
1027 self.vec.as_mut_ptr().offset(idx as isize),
1029 self.vec.set_len(len - (next - idx));
1034 /// Inserts a character into this `String` at a byte position.
1036 /// This is an `O(n)` operation as it requires copying every element in the
1041 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1042 /// lie on a [`char`] boundary.
1044 /// [`char`]: ../../std/primitive.char.html
1051 /// let mut s = String::with_capacity(3);
1053 /// s.insert(0, 'f');
1054 /// s.insert(1, 'o');
1055 /// s.insert(2, 'o');
1057 /// assert_eq!("foo", s);
1060 #[stable(feature = "rust1", since = "1.0.0")]
1061 pub fn insert(&mut self, idx: usize, ch: char) {
1062 assert!(self.is_char_boundary(idx));
1063 let mut bits = [0; 4];
1064 let bits = ch.encode_utf8(&mut bits).as_bytes();
1067 self.insert_bytes(idx, bits);
1071 unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
1072 let len = self.len();
1073 let amt = bytes.len();
1074 self.vec.reserve(amt);
1076 ptr::copy(self.vec.as_ptr().offset(idx as isize),
1077 self.vec.as_mut_ptr().offset((idx + amt) as isize),
1079 ptr::copy(bytes.as_ptr(),
1080 self.vec.as_mut_ptr().offset(idx as isize),
1082 self.vec.set_len(len + amt);
1085 /// Inserts a string slice into this `String` at a byte position.
1087 /// This is an `O(n)` operation as it requires copying every element in the
1092 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1093 /// lie on a [`char`] boundary.
1095 /// [`char`]: ../../std/primitive.char.html
1102 /// let mut s = String::from("bar");
1104 /// s.insert_str(0, "foo");
1106 /// assert_eq!("foobar", s);
1109 #[stable(feature = "insert_str", since = "1.16.0")]
1110 pub fn insert_str(&mut self, idx: usize, string: &str) {
1111 assert!(self.is_char_boundary(idx));
1114 self.insert_bytes(idx, string.as_bytes());
1118 /// Returns a mutable reference to the contents of this `String`.
1122 /// This function is unsafe because it does not check that the bytes passed
1123 /// to it are valid UTF-8. If this constraint is violated, it may cause
1124 /// memory unsafety issues with future users of the `String`, as the rest of
1125 /// the standard library assumes that `String`s are valid UTF-8.
1132 /// let mut s = String::from("hello");
1135 /// let vec = s.as_mut_vec();
1136 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1140 /// assert_eq!(s, "olleh");
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1148 /// Returns the length of this `String`, in bytes.
1155 /// let a = String::from("foo");
1157 /// assert_eq!(a.len(), 3);
1160 #[stable(feature = "rust1", since = "1.0.0")]
1161 pub fn len(&self) -> usize {
1165 /// Returns `true` if this `String` has a length of zero.
1167 /// Returns `false` otherwise.
1174 /// let mut v = String::new();
1175 /// assert!(v.is_empty());
1178 /// assert!(!v.is_empty());
1181 #[stable(feature = "rust1", since = "1.0.0")]
1182 pub fn is_empty(&self) -> bool {
1186 /// Splits the string into two at the given index.
1188 /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1189 /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1190 /// boundary of a UTF-8 code point.
1192 /// Note that the capacity of `self` does not change.
1196 /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1197 /// code point of the string.
1203 /// let mut hello = String::from("Hello, World!");
1204 /// let world = hello.split_off(7);
1205 /// assert_eq!(hello, "Hello, ");
1206 /// assert_eq!(world, "World!");
1210 #[stable(feature = "string_split_off", since = "1.16.0")]
1211 pub fn split_off(&mut self, at: usize) -> String {
1212 assert!(self.is_char_boundary(at));
1213 let other = self.vec.split_off(at);
1214 unsafe { String::from_utf8_unchecked(other) }
1217 /// Truncates this `String`, removing all contents.
1219 /// While this means the `String` will have a length of zero, it does not
1220 /// touch its capacity.
1227 /// let mut s = String::from("foo");
1231 /// assert!(s.is_empty());
1232 /// assert_eq!(0, s.len());
1233 /// assert_eq!(3, s.capacity());
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 pub fn clear(&mut self) {
1241 /// Creates a draining iterator that removes the specified range in the string
1242 /// and yields the removed chars.
1244 /// Note: The element range is removed even if the iterator is not
1245 /// consumed until the end.
1249 /// Panics if the starting point or end point do not lie on a [`char`]
1250 /// boundary, or if they're out of bounds.
1252 /// [`char`]: ../../std/primitive.char.html
1259 /// let mut s = String::from("α is alpha, β is beta");
1260 /// let beta_offset = s.find('β').unwrap_or(s.len());
1262 /// // Remove the range up until the β from the string
1263 /// let t: String = s.drain(..beta_offset).collect();
1264 /// assert_eq!(t, "α is alpha, ");
1265 /// assert_eq!(s, "β is beta");
1267 /// // A full range clears the string
1269 /// assert_eq!(s, "");
1271 #[stable(feature = "drain", since = "1.6.0")]
1272 pub fn drain<R>(&mut self, range: R) -> Drain
1273 where R: RangeArgument<usize>
1277 // The String version of Drain does not have the memory safety issues
1278 // of the vector version. The data is just plain bytes.
1279 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1280 // the removal will not happen.
1281 let len = self.len();
1282 let start = match range.start() {
1284 Excluded(&n) => n + 1,
1287 let end = match range.end() {
1288 Included(&n) => n + 1,
1293 // Take out two simultaneous borrows. The &mut String won't be accessed
1294 // until iteration is over, in Drop.
1295 let self_ptr = self as *mut _;
1296 // slicing does the appropriate bounds checks
1297 let chars_iter = self[start..end].chars();
1307 /// Creates a splicing iterator that removes the specified range in the string,
1308 /// replaces with the given string, and yields the removed chars.
1309 /// The given string doesn’t need to be the same length as the range.
1311 /// Note: The element range is removed when the `Splice` is dropped,
1312 /// even if the iterator is not consumed until the end.
1316 /// Panics if the starting point or end point do not lie on a [`char`]
1317 /// boundary, or if they're out of bounds.
1319 /// [`char`]: ../../std/primitive.char.html
1326 /// #![feature(splice)]
1327 /// let mut s = String::from("α is alpha, β is beta");
1328 /// let beta_offset = s.find('β').unwrap_or(s.len());
1330 /// // Replace the range up until the β from the string
1331 /// let t: String = s.splice(..beta_offset, "Α is capital alpha; ").collect();
1332 /// assert_eq!(t, "α is alpha, ");
1333 /// assert_eq!(s, "Α is capital alpha; β is beta");
1335 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
1336 pub fn splice<'a, 'b, R>(&'a mut self, range: R, replace_with: &'b str) -> Splice<'a, 'b>
1337 where R: RangeArgument<usize>
1341 // The String version of Splice does not have the memory safety issues
1342 // of the vector version. The data is just plain bytes.
1343 // Because the range removal happens in Drop, if the Splice iterator is leaked,
1344 // the removal will not happen.
1345 let len = self.len();
1346 let start = match range.start() {
1348 Excluded(&n) => n + 1,
1351 let end = match range.end() {
1352 Included(&n) => n + 1,
1357 // Take out two simultaneous borrows. The &mut String won't be accessed
1358 // until iteration is over, in Drop.
1359 let self_ptr = self as *mut _;
1360 // slicing does the appropriate bounds checks
1361 let chars_iter = self[start..end].chars();
1368 replace_with: replace_with
1372 /// Converts this `String` into a `Box<str>`.
1374 /// This will drop any excess capacity.
1381 /// let s = String::from("hello");
1383 /// let b = s.into_boxed_str();
1385 #[stable(feature = "box_str", since = "1.4.0")]
1386 pub fn into_boxed_str(self) -> Box<str> {
1387 let slice = self.vec.into_boxed_slice();
1388 unsafe { from_boxed_utf8_unchecked(slice) }
1392 impl FromUtf8Error {
1393 /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
1400 /// #![feature(from_utf8_error_as_bytes)]
1401 /// // some invalid bytes, in a vector
1402 /// let bytes = vec![0, 159];
1404 /// let value = String::from_utf8(bytes);
1406 /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1408 #[unstable(feature = "from_utf8_error_as_bytes", reason = "recently added", issue = "40895")]
1409 pub fn as_bytes(&self) -> &[u8] {
1413 /// Returns the bytes that were attempted to convert to a `String`.
1415 /// This method is carefully constructed to avoid allocation. It will
1416 /// consume the error, moving out the bytes, so that a copy of the bytes
1417 /// does not need to be made.
1424 /// // some invalid bytes, in a vector
1425 /// let bytes = vec![0, 159];
1427 /// let value = String::from_utf8(bytes);
1429 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1431 #[stable(feature = "rust1", since = "1.0.0")]
1432 pub fn into_bytes(self) -> Vec<u8> {
1436 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1438 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1439 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1440 /// an analogue to `FromUtf8Error`. See its documentation for more details
1443 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
1444 /// [`std::str`]: ../../std/str/index.html
1445 /// [`u8`]: ../../std/primitive.u8.html
1446 /// [`&str`]: ../../std/primitive.str.html
1453 /// // some invalid bytes, in a vector
1454 /// let bytes = vec![0, 159];
1456 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1458 /// // the first byte is invalid here
1459 /// assert_eq!(1, error.valid_up_to());
1461 #[stable(feature = "rust1", since = "1.0.0")]
1462 pub fn utf8_error(&self) -> Utf8Error {
1467 #[stable(feature = "rust1", since = "1.0.0")]
1468 impl fmt::Display for FromUtf8Error {
1469 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1470 fmt::Display::fmt(&self.error, f)
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 impl fmt::Display for FromUtf16Error {
1476 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1477 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1481 #[stable(feature = "rust1", since = "1.0.0")]
1482 impl Clone for String {
1483 fn clone(&self) -> Self {
1484 String { vec: self.vec.clone() }
1487 fn clone_from(&mut self, source: &Self) {
1488 self.vec.clone_from(&source.vec);
1492 #[stable(feature = "rust1", since = "1.0.0")]
1493 impl FromIterator<char> for String {
1494 fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1495 let mut buf = String::new();
1501 #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
1502 impl<'a> FromIterator<&'a char> for String {
1503 fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
1504 let mut buf = String::new();
1510 #[stable(feature = "rust1", since = "1.0.0")]
1511 impl<'a> FromIterator<&'a str> for String {
1512 fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1513 let mut buf = String::new();
1519 #[stable(feature = "extend_string", since = "1.4.0")]
1520 impl FromIterator<String> for String {
1521 fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1522 let mut buf = String::new();
1528 #[stable(feature = "herd_cows", since = "1.19.0")]
1529 impl<'a> FromIterator<Cow<'a, str>> for String {
1530 fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> String {
1531 let mut buf = String::new();
1537 #[stable(feature = "rust1", since = "1.0.0")]
1538 impl Extend<char> for String {
1539 fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1540 let iterator = iter.into_iter();
1541 let (lower_bound, _) = iterator.size_hint();
1542 self.reserve(lower_bound);
1543 for ch in iterator {
1549 #[stable(feature = "extend_ref", since = "1.2.0")]
1550 impl<'a> Extend<&'a char> for String {
1551 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1552 self.extend(iter.into_iter().cloned());
1556 #[stable(feature = "rust1", since = "1.0.0")]
1557 impl<'a> Extend<&'a str> for String {
1558 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1565 #[stable(feature = "extend_string", since = "1.4.0")]
1566 impl Extend<String> for String {
1567 fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1574 #[stable(feature = "herd_cows", since = "1.19.0")]
1575 impl<'a> Extend<Cow<'a, str>> for String {
1576 fn extend<I: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: I) {
1583 /// A convenience impl that delegates to the impl for `&str`
1584 #[unstable(feature = "pattern",
1585 reason = "API not fully fleshed out and ready to be stabilized",
1587 impl<'a, 'b> Pattern<'a> for &'b String {
1588 type Searcher = <&'b str as Pattern<'a>>::Searcher;
1590 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1591 self[..].into_searcher(haystack)
1595 fn is_contained_in(self, haystack: &'a str) -> bool {
1596 self[..].is_contained_in(haystack)
1600 fn is_prefix_of(self, haystack: &'a str) -> bool {
1601 self[..].is_prefix_of(haystack)
1605 #[stable(feature = "rust1", since = "1.0.0")]
1606 impl PartialEq for String {
1608 fn eq(&self, other: &String) -> bool {
1609 PartialEq::eq(&self[..], &other[..])
1612 fn ne(&self, other: &String) -> bool {
1613 PartialEq::ne(&self[..], &other[..])
1617 macro_rules! impl_eq {
1618 ($lhs:ty, $rhs: ty) => {
1619 #[stable(feature = "rust1", since = "1.0.0")]
1620 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1622 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1624 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1627 #[stable(feature = "rust1", since = "1.0.0")]
1628 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1630 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1632 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1638 impl_eq! { String, str }
1639 impl_eq! { String, &'a str }
1640 impl_eq! { Cow<'a, str>, str }
1641 impl_eq! { Cow<'a, str>, &'b str }
1642 impl_eq! { Cow<'a, str>, String }
1644 #[stable(feature = "rust1", since = "1.0.0")]
1645 impl Default for String {
1646 /// Creates an empty `String`.
1648 fn default() -> String {
1653 #[stable(feature = "rust1", since = "1.0.0")]
1654 impl fmt::Display for String {
1656 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1657 fmt::Display::fmt(&**self, f)
1661 #[stable(feature = "rust1", since = "1.0.0")]
1662 impl fmt::Debug for String {
1664 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1665 fmt::Debug::fmt(&**self, f)
1669 #[stable(feature = "rust1", since = "1.0.0")]
1670 impl hash::Hash for String {
1672 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1673 (**self).hash(hasher)
1677 /// Implements the `+` operator for concatenating two strings.
1679 /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
1680 /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
1681 /// every operation, which would lead to `O(n^2)` running time when building an `n`-byte string by
1682 /// repeated concatenation.
1684 /// The string on the right-hand side is only borrowed; its contents are copied into the returned
1689 /// Concatenating two `String`s takes the first by value and borrows the second:
1692 /// let a = String::from("hello");
1693 /// let b = String::from(" world");
1695 /// // `a` is moved and can no longer be used here.
1698 /// If you want to keep using the first `String`, you can clone it and append to the clone instead:
1701 /// let a = String::from("hello");
1702 /// let b = String::from(" world");
1703 /// let c = a.clone() + &b;
1704 /// // `a` is still valid here.
1707 /// Concatenating `&str` slices can be done by converting the first to a `String`:
1710 /// let a = "hello";
1711 /// let b = " world";
1712 /// let c = a.to_string() + b;
1714 #[stable(feature = "rust1", since = "1.0.0")]
1715 impl<'a> Add<&'a str> for String {
1716 type Output = String;
1719 fn add(mut self, other: &str) -> String {
1720 self.push_str(other);
1725 /// Implements the `+=` operator for appending to a `String`.
1727 /// This has the same behavior as the [`push_str`] method.
1729 /// [`push_str`]: struct.String.html#method.push_str
1730 #[stable(feature = "stringaddassign", since = "1.12.0")]
1731 impl<'a> AddAssign<&'a str> for String {
1733 fn add_assign(&mut self, other: &str) {
1734 self.push_str(other);
1738 #[stable(feature = "rust1", since = "1.0.0")]
1739 impl ops::Index<ops::Range<usize>> for String {
1743 fn index(&self, index: ops::Range<usize>) -> &str {
1747 #[stable(feature = "rust1", since = "1.0.0")]
1748 impl ops::Index<ops::RangeTo<usize>> for String {
1752 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1756 #[stable(feature = "rust1", since = "1.0.0")]
1757 impl ops::Index<ops::RangeFrom<usize>> for String {
1761 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1765 #[stable(feature = "rust1", since = "1.0.0")]
1766 impl ops::Index<ops::RangeFull> for String {
1770 fn index(&self, _index: ops::RangeFull) -> &str {
1771 unsafe { str::from_utf8_unchecked(&self.vec) }
1774 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1775 impl ops::Index<ops::RangeInclusive<usize>> for String {
1779 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1780 Index::index(&**self, index)
1783 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1784 impl ops::Index<ops::RangeToInclusive<usize>> for String {
1788 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1789 Index::index(&**self, index)
1793 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1794 impl ops::IndexMut<ops::Range<usize>> for String {
1796 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1797 &mut self[..][index]
1800 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1801 impl ops::IndexMut<ops::RangeTo<usize>> for String {
1803 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1804 &mut self[..][index]
1807 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1808 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
1810 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1811 &mut self[..][index]
1814 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1815 impl ops::IndexMut<ops::RangeFull> for String {
1817 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1818 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
1821 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1822 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
1824 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
1825 IndexMut::index_mut(&mut **self, index)
1828 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1829 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
1831 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
1832 IndexMut::index_mut(&mut **self, index)
1836 #[stable(feature = "rust1", since = "1.0.0")]
1837 impl ops::Deref for String {
1841 fn deref(&self) -> &str {
1842 unsafe { str::from_utf8_unchecked(&self.vec) }
1846 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1847 impl ops::DerefMut for String {
1849 fn deref_mut(&mut self) -> &mut str {
1850 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
1854 /// An error when parsing a `String`.
1856 /// This `enum` is slightly awkward: it will never actually exist. This error is
1857 /// part of the type signature of the implementation of [`FromStr`] on
1858 /// [`String`]. The return type of [`from_str`], requires that an error be
1859 /// defined, but, given that a [`String`] can always be made into a new
1860 /// [`String`] without error, this type will never actually be returned. As
1861 /// such, it is only here to satisfy said signature, and is useless otherwise.
1863 /// [`FromStr`]: ../../std/str/trait.FromStr.html
1864 /// [`String`]: struct.String.html
1865 /// [`from_str`]: ../../std/str/trait.FromStr.html#tymethod.from_str
1866 #[stable(feature = "str_parse_error", since = "1.5.0")]
1868 pub enum ParseError {}
1870 #[stable(feature = "rust1", since = "1.0.0")]
1871 impl FromStr for String {
1872 type Err = ParseError;
1874 fn from_str(s: &str) -> Result<String, ParseError> {
1879 #[stable(feature = "str_parse_error", since = "1.5.0")]
1880 impl Clone for ParseError {
1881 fn clone(&self) -> ParseError {
1886 #[stable(feature = "str_parse_error", since = "1.5.0")]
1887 impl fmt::Debug for ParseError {
1888 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1893 #[stable(feature = "str_parse_error2", since = "1.8.0")]
1894 impl fmt::Display for ParseError {
1895 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1900 #[stable(feature = "str_parse_error", since = "1.5.0")]
1901 impl PartialEq for ParseError {
1902 fn eq(&self, _: &ParseError) -> bool {
1907 #[stable(feature = "str_parse_error", since = "1.5.0")]
1908 impl Eq for ParseError {}
1910 /// A trait for converting a value to a `String`.
1912 /// This trait is automatically implemented for any type which implements the
1913 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
1914 /// [`Display`] should be implemented instead, and you get the `ToString`
1915 /// implementation for free.
1917 /// [`Display`]: ../../std/fmt/trait.Display.html
1918 #[stable(feature = "rust1", since = "1.0.0")]
1919 pub trait ToString {
1920 /// Converts the given value to a `String`.
1928 /// let five = String::from("5");
1930 /// assert_eq!(five, i.to_string());
1932 #[stable(feature = "rust1", since = "1.0.0")]
1933 fn to_string(&self) -> String;
1938 /// In this implementation, the `to_string` method panics
1939 /// if the `Display` implementation returns an error.
1940 /// This indicates an incorrect `Display` implementation
1941 /// since `fmt::Write for String` never returns an error itself.
1942 #[stable(feature = "rust1", since = "1.0.0")]
1943 impl<T: fmt::Display + ?Sized> ToString for T {
1945 default fn to_string(&self) -> String {
1946 use core::fmt::Write;
1947 let mut buf = String::new();
1948 buf.write_fmt(format_args!("{}", self))
1949 .expect("a Display implementation return an error unexpectedly");
1950 buf.shrink_to_fit();
1955 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
1956 impl ToString for str {
1958 fn to_string(&self) -> String {
1963 #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")]
1964 impl<'a> ToString for Cow<'a, str> {
1966 fn to_string(&self) -> String {
1971 #[stable(feature = "string_to_string_specialization", since = "1.17.0")]
1972 impl ToString for String {
1974 fn to_string(&self) -> String {
1979 #[stable(feature = "rust1", since = "1.0.0")]
1980 impl AsRef<str> for String {
1982 fn as_ref(&self) -> &str {
1987 #[stable(feature = "rust1", since = "1.0.0")]
1988 impl AsRef<[u8]> for String {
1990 fn as_ref(&self) -> &[u8] {
1995 #[stable(feature = "rust1", since = "1.0.0")]
1996 impl<'a> From<&'a str> for String {
1997 fn from(s: &'a str) -> String {
2002 // note: test pulls in libstd, which causes errors here
2004 #[stable(feature = "string_from_box", since = "1.18.0")]
2005 impl From<Box<str>> for String {
2006 fn from(s: Box<str>) -> String {
2011 #[stable(feature = "box_from_str", since = "1.18.0")]
2012 impl Into<Box<str>> for String {
2013 fn into(self) -> Box<str> {
2014 self.into_boxed_str()
2018 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
2019 impl<'a> From<Cow<'a, str>> for String {
2020 fn from(s: Cow<'a, str>) -> String {
2025 #[stable(feature = "rust1", since = "1.0.0")]
2026 impl<'a> From<&'a str> for Cow<'a, str> {
2028 fn from(s: &'a str) -> Cow<'a, str> {
2033 #[stable(feature = "rust1", since = "1.0.0")]
2034 impl<'a> From<String> for Cow<'a, str> {
2036 fn from(s: String) -> Cow<'a, str> {
2041 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2042 impl<'a> FromIterator<char> for Cow<'a, str> {
2043 fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
2044 Cow::Owned(FromIterator::from_iter(it))
2048 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2049 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
2050 fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
2051 Cow::Owned(FromIterator::from_iter(it))
2055 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2056 impl<'a> FromIterator<String> for Cow<'a, str> {
2057 fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
2058 Cow::Owned(FromIterator::from_iter(it))
2062 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
2063 impl From<String> for Vec<u8> {
2064 fn from(string: String) -> Vec<u8> {
2069 #[stable(feature = "rust1", since = "1.0.0")]
2070 impl fmt::Write for String {
2072 fn write_str(&mut self, s: &str) -> fmt::Result {
2078 fn write_char(&mut self, c: char) -> fmt::Result {
2084 /// A draining iterator for `String`.
2086 /// This struct is created by the [`drain`] method on [`String`]. See its
2087 /// documentation for more.
2089 /// [`drain`]: struct.String.html#method.drain
2090 /// [`String`]: struct.String.html
2091 #[stable(feature = "drain", since = "1.6.0")]
2092 pub struct Drain<'a> {
2093 /// Will be used as &'a mut String in the destructor
2094 string: *mut String,
2095 /// Start of part to remove
2097 /// End of part to remove
2099 /// Current remaining range to remove
2103 #[stable(feature = "collection_debug", since = "1.17.0")]
2104 impl<'a> fmt::Debug for Drain<'a> {
2105 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2106 f.pad("Drain { .. }")
2110 #[stable(feature = "drain", since = "1.6.0")]
2111 unsafe impl<'a> Sync for Drain<'a> {}
2112 #[stable(feature = "drain", since = "1.6.0")]
2113 unsafe impl<'a> Send for Drain<'a> {}
2115 #[stable(feature = "drain", since = "1.6.0")]
2116 impl<'a> Drop for Drain<'a> {
2117 fn drop(&mut self) {
2119 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2120 // panic code being inserted again.
2121 let self_vec = (*self.string).as_mut_vec();
2122 if self.start <= self.end && self.end <= self_vec.len() {
2123 self_vec.drain(self.start..self.end);
2129 #[stable(feature = "drain", since = "1.6.0")]
2130 impl<'a> Iterator for Drain<'a> {
2134 fn next(&mut self) -> Option<char> {
2138 fn size_hint(&self) -> (usize, Option<usize>) {
2139 self.iter.size_hint()
2143 #[stable(feature = "drain", since = "1.6.0")]
2144 impl<'a> DoubleEndedIterator for Drain<'a> {
2146 fn next_back(&mut self) -> Option<char> {
2147 self.iter.next_back()
2151 #[unstable(feature = "fused", issue = "35602")]
2152 impl<'a> FusedIterator for Drain<'a> {}
2154 /// A splicing iterator for `String`.
2156 /// This struct is created by the [`splice()`] method on [`String`]. See its
2157 /// documentation for more.
2159 /// [`splice()`]: struct.String.html#method.splice
2160 /// [`String`]: struct.String.html
2162 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2163 pub struct Splice<'a, 'b> {
2164 /// Will be used as &'a mut String in the destructor
2165 string: *mut String,
2166 /// Start of part to remove
2168 /// End of part to remove
2170 /// Current remaining range to remove
2172 replace_with: &'b str,
2175 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2176 unsafe impl<'a, 'b> Sync for Splice<'a, 'b> {}
2177 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2178 unsafe impl<'a, 'b> Send for Splice<'a, 'b> {}
2180 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2181 impl<'a, 'b> Drop for Splice<'a, 'b> {
2182 fn drop(&mut self) {
2184 let vec = (*self.string).as_mut_vec();
2185 vec.splice(self.start..self.end, self.replace_with.bytes());
2190 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2191 impl<'a, 'b> Iterator for Splice<'a, 'b> {
2195 fn next(&mut self) -> Option<char> {
2199 fn size_hint(&self) -> (usize, Option<usize>) {
2200 self.iter.size_hint()
2204 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2205 impl<'a, 'b> DoubleEndedIterator for Splice<'a, 'b> {
2207 fn next_back(&mut self) -> Option<char> {
2208 self.iter.next_back()