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 //! [`String`]: struct.String.html
18 //! [`ToString`]: trait.ToString.html
22 //! There are multiple ways to create a new `String` from a string literal:
25 //! let s = "Hello".to_string();
27 //! let s = String::from("world");
28 //! let s: String = "also this".into();
31 //! You can create a new `String` from an existing one by concatenating with
35 //! let s = "Hello".to_string();
37 //! let message = s + " world!";
40 //! If you have a vector of valid UTF-8 bytes, you can make a `String` out of
41 //! it. You can do the reverse too.
44 //! let sparkle_heart = vec![240, 159, 146, 150];
46 //! // We know these bytes are valid, so we'll use `unwrap()`.
47 //! let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
49 //! assert_eq!("💖", sparkle_heart);
51 //! let bytes = sparkle_heart.into_bytes();
53 //! assert_eq!(bytes, [240, 159, 146, 150]);
56 #![stable(feature = "rust1", since = "1.0.0")]
60 use core::iter::FromIterator;
62 use core::ops::{self, Add};
65 use core::str::pattern::Pattern;
66 use rustc_unicode::char::{decode_utf16, REPLACEMENT_CHARACTER};
67 use rustc_unicode::str as unicode_str;
70 use borrow::{Cow, IntoCow};
71 use range::RangeArgument;
72 use str::{self, FromStr, Utf8Error, Chars};
76 /// A UTF-8 encoded, growable string.
78 /// The `String` type is the most common string type that has ownership over the
79 /// contents of the string. It has a close relationship with its borrowed
80 /// counterpart, the primitive [`str`].
82 /// [`str`]: ../primitive.str.html
86 /// You can create a `String` from a literal string with `String::from`:
89 /// let hello = String::from("Hello, world!");
92 /// You can append a [`char`] to a `String` with the [`push()`] method, and
93 /// append a [`&str`] with the [`push_str()`] method:
96 /// let mut hello = String::from("Hello, ");
99 /// hello.push_str("orld!");
102 /// [`char`]: ../primitive.char.html
103 /// [`push()`]: #method.push
104 /// [`push_str()`]: #method.push_str
106 /// If you have a vector of UTF-8 bytes, you can create a `String` from it with
107 /// the [`from_utf8()`] method:
110 /// // some bytes, in a vector
111 /// let sparkle_heart = vec![240, 159, 146, 150];
113 /// // We know these bytes are valid, so we'll use `unwrap()`.
114 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
116 /// assert_eq!("💖", sparkle_heart);
119 /// [`from_utf8()`]: #method.from_utf8
123 /// `String`s are always valid UTF-8. This has a few implications, the first of
124 /// which is that if you need a non-UTF-8 string, consider [`OsString`]. It is
125 /// similar, but without the UTF-8 constraint. The second implication is that
126 /// you cannot index into a `String`:
131 /// println!("The first letter of s is {}", s[0]); // ERROR!!!
134 /// [`OsString`]: ../ffi/struct.OsString.html
136 /// Indexing is intended to be a constant-time operation, but UTF-8 encoding
137 /// does not allow us to do this. Furtheremore, it's not clear what sort of
138 /// thing the index should return: a byte, a codepoint, or a grapheme cluster.
139 /// The [`as_bytes()`] and [`chars()`] methods return iterators over the first
140 /// two, respectively.
142 /// [`as_bytes()`]: #method.as_bytes
143 /// [`chars()`]: #method.chars
147 /// `String`s implement [`Deref`]`<Target=str>`, and so inherit all of [`str`]'s
148 /// methods. In addition, this means that you can pass a `String` to any
149 /// function which takes a [`&str`] by using an ampersand (`&`):
152 /// fn takes_str(s: &str) { }
154 /// let s = String::from("Hello");
159 /// [`&str`]: ../primitive.str.html
160 /// [`Deref`]: ../ops/trait.Deref.html
162 /// This will create a [`&str`] from the `String` and pass it in. This
163 /// conversion is very inexpensive, and so generally, functions will accept
164 /// [`&str`]s as arguments unless they need a `String` for some specific reason.
169 /// A `String` is made up of three components: a pointer to some bytes, a
170 /// length, and a capacity. The pointer points to an internal buffer `String`
171 /// uses to store its data. The length is the number of bytes currently stored
172 /// in the buffer, and the capacity is the size of the buffer in bytes. As such,
173 /// the length will always be less than or equal to the capacity.
175 /// This buffer is always stored on the heap.
177 /// You can look at these with the [`as_ptr()`], [`len()`], and [`capacity()`]
183 /// let story = String::from("Once upon a time...");
185 /// let ptr = story.as_ptr();
186 /// let len = story.len();
187 /// let capacity = story.capacity();
189 /// // story has thirteen bytes
190 /// assert_eq!(19, len);
192 /// // Now that we have our parts, we throw the story away.
193 /// mem::forget(story);
195 /// // We can re-build a String out of ptr, len, and capacity. This is all
196 /// // unsafe because we are responsible for making sure the components are
198 /// let s = unsafe { String::from_raw_parts(ptr as *mut _, len, capacity) } ;
200 /// assert_eq!(String::from("Once upon a time..."), s);
203 /// [`as_ptr()`]: #method.as_ptr
204 /// [`len()`]: #method.len
205 /// [`capacity()`]: #method.capacity
207 /// If a `String` has enough capacity, adding elements to it will not
208 /// re-allocate. For example, consider this program:
211 /// let mut s = String::new();
213 /// println!("{}", s.capacity());
216 /// s.push_str("hello");
217 /// println!("{}", s.capacity());
221 /// This will output the following:
232 /// At first, we have no memory allocated at all, but as we append to the
233 /// string, it increases its capacity appropriately. If we instead use the
234 /// [`with_capacity()`] method to allocate the correct capacity initially:
237 /// let mut s = String::with_capacity(25);
239 /// println!("{}", s.capacity());
242 /// s.push_str("hello");
243 /// println!("{}", s.capacity());
247 /// [`with_capacity()`]: #method.with_capacity
249 /// We end up with a different output:
260 /// Here, there's no need to allocate more memory inside the loop.
261 #[derive(PartialOrd, Eq, Ord)]
262 #[stable(feature = "rust1", since = "1.0.0")]
267 /// A possible error value when converting a `String` from a UTF-8 byte vector.
269 /// This type is the error type for the [`from_utf8()`] method on [`String`]. It
270 /// is designed in such a way to carefully avoid reallocations: the
271 /// [`into_bytes()`] method will give back the byte vector that was used in the
272 /// conversion attempt.
274 /// [`from_utf8()`]: struct.String.html#method.from_utf8
275 /// [`String`]: struct.String.html
276 /// [`into_bytes()`]: struct.FromUtf8Error.html#method.into_bytes
278 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
279 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
280 /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
281 /// through the [`utf8_error()`] method.
283 /// [`Utf8Error`]: ../str/struct.Utf8Error.html
284 /// [`std::str`]: ../str/index.html
285 /// [`u8`]: ../primitive.u8.html
286 /// [`&str`]: ../primitive.str.html
287 /// [`utf8_error()`]: #method.utf8_error
294 /// // some invalid bytes, in a vector
295 /// let bytes = vec![0, 159];
297 /// let value = String::from_utf8(bytes);
299 /// assert!(value.is_err());
300 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
302 #[stable(feature = "rust1", since = "1.0.0")]
304 pub struct FromUtf8Error {
309 /// A possible error value when converting a `String` from a UTF-16 byte slice.
311 /// This type is the error type for the [`from_utf16()`] method on [`String`].
313 /// [`from_utf16()`]: struct.String.html#method.from_utf16
314 /// [`String`]: struct.String.html
321 /// // 𝄞mu<invalid>ic
322 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
323 /// 0xD800, 0x0069, 0x0063];
325 /// assert!(String::from_utf16(v).is_err());
327 #[stable(feature = "rust1", since = "1.0.0")]
329 pub struct FromUtf16Error(());
332 /// Creates a new empty `String`.
334 /// Given that the `String` is empty, this will not allocate any initial
335 /// buffer. While that means that this initial operation is very
336 /// inexpensive, but may cause excessive allocation later, when you add
337 /// data. If you have an idea of how much data the `String` will hold,
338 /// consider the [`with_capacity()`] method to prevent excessive
341 /// [`with_capacity()`]: #method.with_capacity
348 /// let s = String::new();
351 #[stable(feature = "rust1", since = "1.0.0")]
352 pub fn new() -> String {
353 String { vec: Vec::new() }
356 /// Creates a new empty `String` with a particular capacity.
358 /// `String`s have an internal buffer to hold their data. The capacity is
359 /// the length of that buffer, and can be queried with the [`capacity()`]
360 /// method. This method creates an empty `String`, but one with an initial
361 /// buffer that can hold `capacity` bytes. This is useful when you may be
362 /// appending a bunch of data to the `String`, reducing the number of
363 /// reallocations it needs to do.
365 /// [`capacity()`]: #method.capacity
367 /// If the given capacity is `0`, no allocation will occur, and this method
368 /// is identical to the [`new()`] method.
370 /// [`new()`]: #method.new
377 /// let mut s = String::with_capacity(10);
379 /// // The String contains no chars, even though it has capacity for more
380 /// assert_eq!(s.len(), 0);
382 /// // These are all done without reallocating...
383 /// let cap = s.capacity();
388 /// assert_eq!(s.capacity(), cap);
390 /// // ...but this may make the vector reallocate
394 #[stable(feature = "rust1", since = "1.0.0")]
395 pub fn with_capacity(capacity: usize) -> String {
396 String { vec: Vec::with_capacity(capacity) }
399 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
400 // required for this method definition, is not available. Since we don't
401 // require this method for testing purposes, I'll just stub it
402 // NB see the slice::hack module in slice.rs for more information
405 pub fn from_str(_: &str) -> String {
406 panic!("not available with cfg(test)");
409 /// Converts a vector of bytes to a `String`.
411 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a vector of bytes
412 /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
413 /// two. Not all byte slices are valid `String`s, however: `String`
414 /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
415 /// the bytes are valid UTF-8, and then does the conversion.
417 /// [`&str`]: ../primitive.str.html
418 /// [`u8`]: ../primitive.u8.html
419 /// [`Vec<u8>`]: ../vec/struct.Vec.html
421 /// If you are sure that the byte slice is valid UTF-8, and you don't want
422 /// to incur the overhead of the validity check, there is an unsafe version
423 /// of this function, [`from_utf8_unchecked()`], which has the same behavior
424 /// but skips the check.
426 /// [`from_utf8_unchecked()`]: struct.String.html#method.from_utf8_unchecked
428 /// This method will take care to not copy the vector, for efficiency's
431 /// If you need a `&str` instead of a `String`, consider
432 /// [`str::from_utf8()`].
434 /// [`str::from_utf8()`]: ../str/fn.from_utf8.html
438 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
439 /// provided bytes are not UTF-8. The vector you moved in is also included.
446 /// // some bytes, in a vector
447 /// let sparkle_heart = vec![240, 159, 146, 150];
449 /// // We know these bytes are valid, so we'll use `unwrap()`.
450 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
452 /// assert_eq!("💖", sparkle_heart);
458 /// // some invalid bytes, in a vector
459 /// let sparkle_heart = vec![0, 159, 146, 150];
461 /// assert!(String::from_utf8(sparkle_heart).is_err());
464 /// See the docs for [`FromUtf8Error`] for more details on what you can do
467 /// [`FromUtf8Error`]: struct.FromUtf8Error.html
469 #[stable(feature = "rust1", since = "1.0.0")]
470 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
471 match str::from_utf8(&vec) {
472 Ok(..) => Ok(String { vec: vec }),
482 /// Converts a slice of bytes to a string, including invalid characters.
484 /// Strings are made of bytes ([`u8`]), and a slice of bytes
485 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
486 /// between the two. Not all byte slices are valid strings, however: strings
487 /// are required to be valid UTF-8. During this conversion,
488 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
489 /// `U+FFFD REPLACEMENT CHARACTER`, which looks like this: �
491 /// [`u8`]: ../primitive.u8.html
492 /// [byteslice]: ../primitive.slice.html
494 /// If you are sure that the byte slice is valid UTF-8, and you don't want
495 /// to incur the overhead of the conversion, there is an unsafe version
496 /// of this function, [`from_utf8_unchecked()`], which has the same behavior
497 /// but skips the checks.
499 /// [`from_utf8_unchecked()`]: struct.String.html#method.from_utf8_unchecked
501 /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
502 /// UTF-8, then we need to insert the replacement characters, which will
503 /// change the size of the string, and hence, require a `String`. But if
504 /// it's already valid UTF-8, we don't need a new allocation. This return
505 /// type allows us to handle both cases.
507 /// [`Cow<'a, str>`]: ../borrow/enum.Cow.html
514 /// // some bytes, in a vector
515 /// let sparkle_heart = vec![240, 159, 146, 150];
517 /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
519 /// assert_eq!("💖", sparkle_heart);
525 /// // some invalid bytes
526 /// let input = b"Hello \xF0\x90\x80World";
527 /// let output = String::from_utf8_lossy(input);
529 /// assert_eq!("Hello �World", output);
531 #[stable(feature = "rust1", since = "1.0.0")]
532 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
534 match str::from_utf8(v) {
535 Ok(s) => return Cow::Borrowed(s),
536 Err(e) => i = e.valid_up_to(),
539 const TAG_CONT_U8: u8 = 128;
540 const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
542 fn unsafe_get(xs: &[u8], i: usize) -> u8 {
543 unsafe { *xs.get_unchecked(i) }
545 fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 {
553 let mut res = String::with_capacity(total);
556 unsafe { res.as_mut_vec().extend_from_slice(&v[..i]) };
559 // subseqidx is the index of the first byte of the subsequence we're
560 // looking at. It's used to copy a bunch of contiguous good codepoints
561 // at once instead of copying them one by one.
562 let mut subseqidx = i;
566 let byte = unsafe_get(v, i);
569 macro_rules! error { () => ({
572 res.as_mut_vec().extend_from_slice(&v[subseqidx..i_]);
575 res.as_mut_vec().extend_from_slice(REPLACEMENT);
580 // subseqidx handles this
582 let w = unicode_str::utf8_char_width(byte);
586 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
593 match (byte, safe_get(v, i, total)) {
594 (0xE0, 0xA0...0xBF) => (),
595 (0xE1...0xEC, 0x80...0xBF) => (),
596 (0xED, 0x80...0x9F) => (),
597 (0xEE...0xEF, 0x80...0xBF) => (),
604 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
611 match (byte, safe_get(v, i, total)) {
612 (0xF0, 0x90...0xBF) => (),
613 (0xF1...0xF3, 0x80...0xBF) => (),
614 (0xF4, 0x80...0x8F) => (),
621 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
626 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
639 if subseqidx < total {
640 unsafe { res.as_mut_vec().extend_from_slice(&v[subseqidx..total]) };
645 /// Decode a UTF-16 encoded vector `v` into a `String`, returning `Err`
646 /// if `v` contains any invalid data.
654 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
655 /// 0x0073, 0x0069, 0x0063];
656 /// assert_eq!(String::from("𝄞music"),
657 /// String::from_utf16(v).unwrap());
659 /// // 𝄞mu<invalid>ic
660 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
661 /// 0xD800, 0x0069, 0x0063];
662 /// assert!(String::from_utf16(v).is_err());
664 #[stable(feature = "rust1", since = "1.0.0")]
665 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
666 decode_utf16(v.iter().cloned()).collect::<Result<_, _>>().map_err(|_| FromUtf16Error(()))
669 /// Decode a UTF-16 encoded vector `v` into a string, replacing
670 /// invalid data with the replacement character (U+FFFD).
677 /// // 𝄞mus<invalid>ic<invalid>
678 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
679 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
682 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
683 /// String::from_utf16_lossy(v));
686 #[stable(feature = "rust1", since = "1.0.0")]
687 pub fn from_utf16_lossy(v: &[u16]) -> String {
688 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
691 /// Creates a new `String` from a length, capacity, and pointer.
695 /// This is highly unsafe, due to the number of invariants that aren't
698 /// * The memory at `ptr` needs to have been previously allocated by the
699 /// same allocator the standard library uses.
700 /// * `length` needs to be less than or equal to `capacity`.
701 /// * `capacity` needs to be the correct value.
703 /// Violating these may cause problems like corrupting the allocator's
704 /// internal datastructures.
714 /// let s = String::from("hello");
715 /// let ptr = s.as_ptr();
716 /// let len = s.len();
717 /// let capacity = s.capacity();
721 /// let s = String::from_raw_parts(ptr as *mut _, len, capacity);
723 /// assert_eq!(String::from("hello"), s);
727 #[stable(feature = "rust1", since = "1.0.0")]
728 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
729 String { vec: Vec::from_raw_parts(buf, length, capacity) }
732 /// Converts a vector of bytes to a `String` without checking that the
733 /// string contains valid UTF-8.
735 /// See the safe version, [`from_utf8()`], for more details.
737 /// [`from_utf8()`]: struct.String.html#method.from_utf8
741 /// This function is unsafe because it does not check that the bytes passed
742 /// to it are valid UTF-8. If this constraint is violated, it may cause
743 /// memory unsafety issues with future users of the `String`, as the rest of
744 /// the standard library assumes that `String`s are valid UTF-8.
751 /// // some bytes, in a vector
752 /// let sparkle_heart = vec![240, 159, 146, 150];
754 /// let sparkle_heart = unsafe {
755 /// String::from_utf8_unchecked(sparkle_heart)
758 /// assert_eq!("💖", sparkle_heart);
761 #[stable(feature = "rust1", since = "1.0.0")]
762 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
763 String { vec: bytes }
766 /// Converts a `String` into a byte vector.
768 /// This consumes the `String`, so we do not need to copy its contents.
775 /// let s = String::from("hello");
776 /// let bytes = s.into_bytes();
778 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
781 #[stable(feature = "rust1", since = "1.0.0")]
782 pub fn into_bytes(self) -> Vec<u8> {
786 /// Extracts a string slice containing the entire string.
788 #[stable(feature = "string_as_str", since = "1.7.0")]
789 pub fn as_str(&self) -> &str {
793 /// Extracts a string slice containing the entire string.
795 #[stable(feature = "string_as_str", since = "1.7.0")]
796 pub fn as_mut_str(&mut self) -> &mut str {
800 /// Appends a given string slice onto the end of this `String`.
807 /// let mut s = String::from("foo");
809 /// s.push_str("bar");
811 /// assert_eq!("foobar", s);
814 #[stable(feature = "rust1", since = "1.0.0")]
815 pub fn push_str(&mut self, string: &str) {
816 self.vec.extend_from_slice(string.as_bytes())
819 /// Returns this `String`'s capacity, in bytes.
826 /// let s = String::with_capacity(10);
828 /// assert!(s.capacity() >= 10);
831 #[stable(feature = "rust1", since = "1.0.0")]
832 pub fn capacity(&self) -> usize {
836 /// Ensures that this `String`'s capacity is at least `additional` bytes
837 /// larger than its length.
839 /// The capacity may be increased by more than `additional` bytes if it
840 /// chooses, to prevent frequent reallocations.
842 /// If you do not want this "at least" behavior, see the [`reserve_exact()`]
845 /// [`reserve_exact()`]: #method.reserve_exact
849 /// Panics if the new capacity overflows `usize`.
856 /// let mut s = String::new();
860 /// assert!(s.capacity() >= 10);
863 /// This may not actually increase the capacity:
866 /// let mut s = String::with_capacity(10);
870 /// // s now has a length of 2 and a capacity of 10
871 /// assert_eq!(2, s.len());
872 /// assert_eq!(10, s.capacity());
874 /// // Since we already have an extra 8 capacity, calling this...
877 /// // ... doesn't actually increase.
878 /// assert_eq!(10, s.capacity());
881 #[stable(feature = "rust1", since = "1.0.0")]
882 pub fn reserve(&mut self, additional: usize) {
883 self.vec.reserve(additional)
886 /// Ensures that this `String`'s capacity is `additional` bytes
887 /// larger than its length.
889 /// Consider using the [`reserve()`] method unless you absolutely know
890 /// better than the allocator.
892 /// [`reserve()`]: #method.reserve
896 /// Panics if the new capacity overflows `usize`.
903 /// let mut s = String::new();
905 /// s.reserve_exact(10);
907 /// assert!(s.capacity() >= 10);
910 /// This may not actually increase the capacity:
913 /// let mut s = String::with_capacity(10);
917 /// // s now has a length of 2 and a capacity of 10
918 /// assert_eq!(2, s.len());
919 /// assert_eq!(10, s.capacity());
921 /// // Since we already have an extra 8 capacity, calling this...
922 /// s.reserve_exact(8);
924 /// // ... doesn't actually increase.
925 /// assert_eq!(10, s.capacity());
928 #[stable(feature = "rust1", since = "1.0.0")]
929 pub fn reserve_exact(&mut self, additional: usize) {
930 self.vec.reserve_exact(additional)
933 /// Shrinks the capacity of this `String` to match its length.
940 /// let mut s = String::from("foo");
943 /// assert!(s.capacity() >= 100);
945 /// s.shrink_to_fit();
946 /// assert_eq!(3, s.capacity());
949 #[stable(feature = "rust1", since = "1.0.0")]
950 pub fn shrink_to_fit(&mut self) {
951 self.vec.shrink_to_fit()
954 /// Appends the given `char` to the end of this `String`.
961 /// let mut s = String::from("abc");
967 /// assert_eq!("abc123", s);
970 #[stable(feature = "rust1", since = "1.0.0")]
971 pub fn push(&mut self, ch: char) {
972 match ch.len_utf8() {
973 1 => self.vec.push(ch as u8),
975 let cur_len = self.len();
976 // This may use up to 4 bytes.
977 self.vec.reserve(ch_len);
980 // Attempt to not use an intermediate buffer by just pushing bytes
981 // directly onto this string.
982 let slice = slice::from_raw_parts_mut(self.vec
984 .offset(cur_len as isize),
986 let used = ch.encode_utf8(slice).unwrap_or(0);
987 self.vec.set_len(cur_len + used);
993 /// Returns a byte slice of this `String`'s contents.
1000 /// let s = String::from("hello");
1002 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
1005 #[stable(feature = "rust1", since = "1.0.0")]
1006 pub fn as_bytes(&self) -> &[u8] {
1010 /// Shortens this `String` to the specified length.
1014 /// Panics if `new_len` > current length, or if `new_len` does not lie on a
1015 /// [`char`] boundary.
1017 /// [`char`]: ../primitive.char.html
1024 /// let mut s = String::from("hello");
1028 /// assert_eq!("he", s);
1031 #[stable(feature = "rust1", since = "1.0.0")]
1032 pub fn truncate(&mut self, new_len: usize) {
1033 assert!(self.is_char_boundary(new_len));
1034 self.vec.truncate(new_len)
1037 /// Removes the last character from the string buffer and returns it.
1039 /// Returns `None` if this `String` is empty.
1046 /// let mut s = String::from("foo");
1048 /// assert_eq!(s.pop(), Some('o'));
1049 /// assert_eq!(s.pop(), Some('o'));
1050 /// assert_eq!(s.pop(), Some('f'));
1052 /// assert_eq!(s.pop(), None);
1055 #[stable(feature = "rust1", since = "1.0.0")]
1056 pub fn pop(&mut self) -> Option<char> {
1057 let len = self.len();
1062 let ch = self.char_at_reverse(len);
1064 self.vec.set_len(len - ch.len_utf8());
1069 /// Removes a `char` from this `String` at a byte position and returns it.
1071 /// This is an `O(n)` operation, as it requires copying every element in the
1076 /// Panics if `idx` is larger than or equal to the `String`'s length,
1077 /// or if it does not lie on a [`char`] boundary.
1079 /// [`char`]: ../primitive.char.html
1086 /// let mut s = String::from("foo");
1088 /// assert_eq!(s.remove(0), 'f');
1089 /// assert_eq!(s.remove(1), 'o');
1090 /// assert_eq!(s.remove(0), 'o');
1093 #[stable(feature = "rust1", since = "1.0.0")]
1094 pub fn remove(&mut self, idx: usize) -> char {
1095 let len = self.len();
1098 let ch = self.char_at(idx);
1099 let next = idx + ch.len_utf8();
1101 ptr::copy(self.vec.as_ptr().offset(next as isize),
1102 self.vec.as_mut_ptr().offset(idx as isize),
1104 self.vec.set_len(len - (next - idx));
1109 /// Inserts a character into this `String` at a byte position.
1111 /// This is an `O(n)` operation as it requires copying every element in the
1116 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1117 /// lie on a [`char`] boundary.
1119 /// [`char`]: ../primitive.char.html
1126 /// let mut s = String::with_capacity(3);
1128 /// s.insert(0, 'f');
1129 /// s.insert(1, 'o');
1130 /// s.insert(2, 'o');
1132 /// assert_eq!("foo", s);
1135 #[stable(feature = "rust1", since = "1.0.0")]
1136 pub fn insert(&mut self, idx: usize, ch: char) {
1137 let len = self.len();
1138 assert!(idx <= len);
1139 assert!(self.is_char_boundary(idx));
1140 self.vec.reserve(4);
1141 let mut bits = [0; 4];
1142 let amt = ch.encode_utf8(&mut bits).unwrap();
1145 ptr::copy(self.vec.as_ptr().offset(idx as isize),
1146 self.vec.as_mut_ptr().offset((idx + amt) as isize),
1148 ptr::copy(bits.as_ptr(),
1149 self.vec.as_mut_ptr().offset(idx as isize),
1151 self.vec.set_len(len + amt);
1155 /// Returns a mutable reference to the contents of this `String`.
1159 /// This function is unsafe because it does not check that the bytes passed
1160 /// to it are valid UTF-8. If this constraint is violated, it may cause
1161 /// memory unsafety issues with future users of the `String`, as the rest of
1162 /// the standard library assumes that `String`s are valid UTF-8.
1169 /// let mut s = String::from("hello");
1172 /// let vec = s.as_mut_vec();
1173 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1177 /// assert_eq!(s, "olleh");
1180 #[stable(feature = "rust1", since = "1.0.0")]
1181 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1185 /// Returns the length of this `String`, in bytes.
1192 /// let a = String::from("foo");
1194 /// assert_eq!(a.len(), 3);
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 pub fn len(&self) -> usize {
1202 /// Returns `true` if this `String` has a length of zero.
1204 /// Returns `false` otherwise.
1211 /// let mut v = String::new();
1212 /// assert!(v.is_empty());
1215 /// assert!(!v.is_empty());
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 pub fn is_empty(&self) -> bool {
1223 /// Truncates this `String`, removing all contents.
1225 /// While this means the `String` will have a length of zero, it does not
1226 /// touch its capacity.
1233 /// let mut s = String::from("foo");
1237 /// assert!(s.is_empty());
1238 /// assert_eq!(0, s.len());
1239 /// assert_eq!(3, s.capacity());
1242 #[stable(feature = "rust1", since = "1.0.0")]
1243 pub fn clear(&mut self) {
1247 /// Create a draining iterator that removes the specified range in the string
1248 /// and yields the removed chars.
1250 /// Note: The element range is removed even if the iterator is not
1251 /// consumed until the end.
1255 /// Panics if the starting point or end point do not lie on a [`char`]
1256 /// boundary, or if they're out of bounds.
1258 /// [`char`]: ../primitive.char.html
1265 /// let mut s = String::from("α is alpha, β is beta");
1266 /// let beta_offset = s.find('β').unwrap_or(s.len());
1268 /// // Remove the range up until the β from the string
1269 /// let t: String = s.drain(..beta_offset).collect();
1270 /// assert_eq!(t, "α is alpha, ");
1271 /// assert_eq!(s, "β is beta");
1273 /// // A full range clears the string
1275 /// assert_eq!(s, "");
1277 #[stable(feature = "drain", since = "1.6.0")]
1278 pub fn drain<R>(&mut self, range: R) -> Drain
1279 where R: RangeArgument<usize>
1283 // The String version of Drain does not have the memory safety issues
1284 // of the vector version. The data is just plain bytes.
1285 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1286 // the removal will not happen.
1287 let len = self.len();
1288 let start = *range.start().unwrap_or(&0);
1289 let end = *range.end().unwrap_or(&len);
1291 // Take out two simultaneous borrows. The &mut String won't be accessed
1292 // until iteration is over, in Drop.
1293 let self_ptr = self as *mut _;
1294 // slicing does the appropriate bounds checks
1295 let chars_iter = self[start..end].chars();
1305 /// Converts this `String` into a `Box<str>`.
1307 /// This will drop any excess capacity.
1314 /// let s = String::from("hello");
1316 /// let b = s.into_boxed_str();
1318 #[stable(feature = "box_str", since = "1.4.0")]
1319 pub fn into_boxed_str(self) -> Box<str> {
1320 let slice = self.vec.into_boxed_slice();
1321 unsafe { mem::transmute::<Box<[u8]>, Box<str>>(slice) }
1325 impl FromUtf8Error {
1326 /// Returns the bytes that were attempted to convert to a `String`.
1328 /// This method is carefully constructed to avoid allocation. It will
1329 /// consume the error, moving out the bytes, so that a copy of the bytes
1330 /// does not need to be made.
1337 /// // some invalid bytes, in a vector
1338 /// let bytes = vec![0, 159];
1340 /// let value = String::from_utf8(bytes);
1342 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1344 #[stable(feature = "rust1", since = "1.0.0")]
1345 pub fn into_bytes(self) -> Vec<u8> {
1349 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1351 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1352 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1353 /// an analogue to `FromUtf8Error`. See its documentation for more details
1356 /// [`Utf8Error`]: ../str/struct.Utf8Error.html
1357 /// [`std::str`]: ../str/index.html
1358 /// [`u8`]: ../primitive.u8.html
1359 /// [`&str`]: ../primitive.str.html
1366 /// // some invalid bytes, in a vector
1367 /// let bytes = vec![0, 159];
1369 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1371 /// // the first byte is invalid here
1372 /// assert_eq!(1, error.valid_up_to());
1374 #[stable(feature = "rust1", since = "1.0.0")]
1375 pub fn utf8_error(&self) -> Utf8Error {
1380 #[stable(feature = "rust1", since = "1.0.0")]
1381 impl fmt::Display for FromUtf8Error {
1382 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1383 fmt::Display::fmt(&self.error, f)
1387 #[stable(feature = "rust1", since = "1.0.0")]
1388 impl fmt::Display for FromUtf16Error {
1389 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1390 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1394 #[stable(feature = "rust1", since = "1.0.0")]
1395 impl Clone for String {
1396 fn clone(&self) -> Self {
1397 String { vec: self.vec.clone() }
1400 fn clone_from(&mut self, source: &Self) {
1401 self.vec.clone_from(&source.vec);
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 impl FromIterator<char> for String {
1407 fn from_iter<I: IntoIterator<Item = char>>(iterable: I) -> String {
1408 let mut buf = String::new();
1409 buf.extend(iterable);
1414 #[stable(feature = "rust1", since = "1.0.0")]
1415 impl<'a> FromIterator<&'a str> for String {
1416 fn from_iter<I: IntoIterator<Item = &'a str>>(iterable: I) -> String {
1417 let mut buf = String::new();
1418 buf.extend(iterable);
1423 #[stable(feature = "extend_string", since = "1.4.0")]
1424 impl FromIterator<String> for String {
1425 fn from_iter<I: IntoIterator<Item = String>>(iterable: I) -> String {
1426 let mut buf = String::new();
1427 buf.extend(iterable);
1432 #[stable(feature = "rust1", since = "1.0.0")]
1433 impl Extend<char> for String {
1434 fn extend<I: IntoIterator<Item = char>>(&mut self, iterable: I) {
1435 let iterator = iterable.into_iter();
1436 let (lower_bound, _) = iterator.size_hint();
1437 self.reserve(lower_bound);
1438 for ch in iterator {
1444 #[stable(feature = "extend_ref", since = "1.2.0")]
1445 impl<'a> Extend<&'a char> for String {
1446 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iterable: I) {
1447 self.extend(iterable.into_iter().cloned());
1451 #[stable(feature = "rust1", since = "1.0.0")]
1452 impl<'a> Extend<&'a str> for String {
1453 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iterable: I) {
1460 #[stable(feature = "extend_string", since = "1.4.0")]
1461 impl Extend<String> for String {
1462 fn extend<I: IntoIterator<Item = String>>(&mut self, iterable: I) {
1469 /// A convenience impl that delegates to the impl for `&str`
1470 #[unstable(feature = "pattern",
1471 reason = "API not fully fleshed out and ready to be stabilized",
1473 impl<'a, 'b> Pattern<'a> for &'b String {
1474 type Searcher = <&'b str as Pattern<'a>>::Searcher;
1476 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1477 self[..].into_searcher(haystack)
1481 fn is_contained_in(self, haystack: &'a str) -> bool {
1482 self[..].is_contained_in(haystack)
1486 fn is_prefix_of(self, haystack: &'a str) -> bool {
1487 self[..].is_prefix_of(haystack)
1491 #[stable(feature = "rust1", since = "1.0.0")]
1492 impl PartialEq for String {
1494 fn eq(&self, other: &String) -> bool {
1495 PartialEq::eq(&self[..], &other[..])
1498 fn ne(&self, other: &String) -> bool {
1499 PartialEq::ne(&self[..], &other[..])
1503 macro_rules! impl_eq {
1504 ($lhs:ty, $rhs: ty) => {
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1508 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1510 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1513 #[stable(feature = "rust1", since = "1.0.0")]
1514 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1516 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1518 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1524 impl_eq! { String, str }
1525 impl_eq! { String, &'a str }
1526 impl_eq! { Cow<'a, str>, str }
1527 impl_eq! { Cow<'a, str>, &'b str }
1528 impl_eq! { Cow<'a, str>, String }
1530 #[stable(feature = "rust1", since = "1.0.0")]
1531 impl Default for String {
1533 fn default() -> String {
1538 #[stable(feature = "rust1", since = "1.0.0")]
1539 impl fmt::Display for String {
1541 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1542 fmt::Display::fmt(&**self, f)
1546 #[stable(feature = "rust1", since = "1.0.0")]
1547 impl fmt::Debug for String {
1549 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1550 fmt::Debug::fmt(&**self, f)
1554 #[stable(feature = "rust1", since = "1.0.0")]
1555 impl hash::Hash for String {
1557 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1558 (**self).hash(hasher)
1562 #[stable(feature = "rust1", since = "1.0.0")]
1563 impl<'a> Add<&'a str> for String {
1564 type Output = String;
1567 fn add(mut self, other: &str) -> String {
1568 self.push_str(other);
1573 #[stable(feature = "rust1", since = "1.0.0")]
1574 impl ops::Index<ops::Range<usize>> for String {
1578 fn index(&self, index: ops::Range<usize>) -> &str {
1582 #[stable(feature = "rust1", since = "1.0.0")]
1583 impl ops::Index<ops::RangeTo<usize>> for String {
1587 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1591 #[stable(feature = "rust1", since = "1.0.0")]
1592 impl ops::Index<ops::RangeFrom<usize>> for String {
1596 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1600 #[stable(feature = "rust1", since = "1.0.0")]
1601 impl ops::Index<ops::RangeFull> for String {
1605 fn index(&self, _index: ops::RangeFull) -> &str {
1606 unsafe { str::from_utf8_unchecked(&self.vec) }
1610 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1611 impl ops::IndexMut<ops::Range<usize>> for String {
1613 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1614 &mut self[..][index]
1617 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1618 impl ops::IndexMut<ops::RangeTo<usize>> for String {
1620 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1621 &mut self[..][index]
1624 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1625 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
1627 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1628 &mut self[..][index]
1631 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1632 impl ops::IndexMut<ops::RangeFull> for String {
1634 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1635 unsafe { mem::transmute(&mut *self.vec) }
1639 #[stable(feature = "rust1", since = "1.0.0")]
1640 impl ops::Deref for String {
1644 fn deref(&self) -> &str {
1645 unsafe { str::from_utf8_unchecked(&self.vec) }
1649 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1650 impl ops::DerefMut for String {
1652 fn deref_mut(&mut self) -> &mut str {
1653 unsafe { mem::transmute(&mut *self.vec) }
1657 /// An error when parsing a `String`.
1659 /// This `enum` is slightly awkward: it will never actually exist. This error is
1660 /// part of the type signature of the implementation of [`FromStr`] on
1661 /// [`String`]. The return type of [`from_str()`], requires that an error be
1662 /// defined, but, given that a [`String`] can always be made into a new
1663 /// [`String`] without error, this type will never actually be returned. As
1664 /// such, it is only here to satisfy said signature, and is useless otherwise.
1666 /// [`FromStr`]: ../str/trait.FromStr.html
1667 /// [`String`]: struct.String.html
1668 /// [`from_str()`]: ../str/trait.FromStr.html#tymethod.from_str
1669 #[stable(feature = "str_parse_error", since = "1.5.0")]
1671 pub enum ParseError {}
1673 #[stable(feature = "rust1", since = "1.0.0")]
1674 impl FromStr for String {
1675 type Err = ParseError;
1677 fn from_str(s: &str) -> Result<String, ParseError> {
1682 #[stable(feature = "str_parse_error", since = "1.5.0")]
1683 impl Clone for ParseError {
1684 fn clone(&self) -> ParseError {
1689 #[stable(feature = "str_parse_error", since = "1.5.0")]
1690 impl fmt::Debug for ParseError {
1691 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1696 #[stable(feature = "str_parse_error2", since = "1.8.0")]
1697 impl fmt::Display for ParseError {
1698 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1703 #[stable(feature = "str_parse_error", since = "1.5.0")]
1704 impl PartialEq for ParseError {
1705 fn eq(&self, _: &ParseError) -> bool {
1710 #[stable(feature = "str_parse_error", since = "1.5.0")]
1711 impl Eq for ParseError {}
1713 /// A trait for converting a value to a `String`.
1715 /// This trait is automatically implemented for any type which implements the
1716 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
1717 /// [`Display`] should be implemented instead, and you get the `ToString`
1718 /// implementation for free.
1720 /// [`Display`]: ../fmt/trait.Display.html
1721 #[stable(feature = "rust1", since = "1.0.0")]
1722 pub trait ToString {
1723 /// Converts the given value to a `String`.
1731 /// let five = String::from("5");
1733 /// assert_eq!(five, i.to_string());
1735 #[stable(feature = "rust1", since = "1.0.0")]
1736 fn to_string(&self) -> String;
1739 #[stable(feature = "rust1", since = "1.0.0")]
1740 impl<T: fmt::Display + ?Sized> ToString for T {
1742 fn to_string(&self) -> String {
1743 use core::fmt::Write;
1744 let mut buf = String::new();
1745 let _ = buf.write_fmt(format_args!("{}", self));
1746 buf.shrink_to_fit();
1751 #[stable(feature = "rust1", since = "1.0.0")]
1752 impl AsRef<str> for String {
1754 fn as_ref(&self) -> &str {
1759 #[stable(feature = "rust1", since = "1.0.0")]
1760 impl AsRef<[u8]> for String {
1762 fn as_ref(&self) -> &[u8] {
1767 #[stable(feature = "rust1", since = "1.0.0")]
1768 impl<'a> From<&'a str> for String {
1771 fn from(s: &'a str) -> String {
1772 String { vec: <[_]>::to_vec(s.as_bytes()) }
1775 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1776 // required for this method definition, is not available. Since we don't
1777 // require this method for testing purposes, I'll just stub it
1778 // NB see the slice::hack module in slice.rs for more information
1781 fn from(_: &str) -> String {
1782 panic!("not available with cfg(test)");
1786 #[stable(feature = "rust1", since = "1.0.0")]
1787 impl<'a> From<&'a str> for Cow<'a, str> {
1789 fn from(s: &'a str) -> Cow<'a, str> {
1794 #[stable(feature = "rust1", since = "1.0.0")]
1795 impl<'a> From<String> for Cow<'a, str> {
1797 fn from(s: String) -> Cow<'a, str> {
1802 #[stable(feature = "rust1", since = "1.0.0")]
1803 impl Into<Vec<u8>> for String {
1804 fn into(self) -> Vec<u8> {
1809 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`",
1811 #[allow(deprecated)]
1812 impl IntoCow<'static, str> for String {
1814 fn into_cow(self) -> Cow<'static, str> {
1819 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`",
1821 #[allow(deprecated)]
1822 impl<'a> IntoCow<'a, str> for &'a str {
1824 fn into_cow(self) -> Cow<'a, str> {
1829 #[stable(feature = "rust1", since = "1.0.0")]
1830 impl fmt::Write for String {
1832 fn write_str(&mut self, s: &str) -> fmt::Result {
1838 fn write_char(&mut self, c: char) -> fmt::Result {
1844 /// A draining iterator for `String`.
1846 /// This struct is created by the [`drain()`] method on [`String`]. See its
1847 /// documentation for more.
1849 /// [`drain()`]: struct.String.html#method.drain
1850 /// [`String`]: struct.String.html
1851 #[stable(feature = "drain", since = "1.6.0")]
1852 pub struct Drain<'a> {
1853 /// Will be used as &'a mut String in the destructor
1854 string: *mut String,
1855 /// Start of part to remove
1857 /// End of part to remove
1859 /// Current remaining range to remove
1863 #[stable(feature = "drain", since = "1.6.0")]
1864 unsafe impl<'a> Sync for Drain<'a> {}
1865 #[stable(feature = "drain", since = "1.6.0")]
1866 unsafe impl<'a> Send for Drain<'a> {}
1868 #[stable(feature = "drain", since = "1.6.0")]
1869 impl<'a> Drop for Drain<'a> {
1870 fn drop(&mut self) {
1872 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
1873 // panic code being inserted again.
1874 let self_vec = (*self.string).as_mut_vec();
1875 if self.start <= self.end && self.end <= self_vec.len() {
1876 self_vec.drain(self.start..self.end);
1882 #[stable(feature = "drain", since = "1.6.0")]
1883 impl<'a> Iterator for Drain<'a> {
1887 fn next(&mut self) -> Option<char> {
1891 fn size_hint(&self) -> (usize, Option<usize>) {
1892 self.iter.size_hint()
1896 #[stable(feature = "drain", since = "1.6.0")]
1897 impl<'a> DoubleEndedIterator for Drain<'a> {
1899 fn next_back(&mut self) -> Option<char> {
1900 self.iter.next_back()