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
20 #![stable(feature = "rust1", since = "1.0.0")]
24 use core::iter::FromIterator;
26 use core::ops::{self, Add};
29 use core::str::pattern::Pattern;
30 use rustc_unicode::char::{decode_utf16, REPLACEMENT_CHARACTER};
31 use rustc_unicode::str as unicode_str;
33 use borrow::{Cow, IntoCow};
34 use range::RangeArgument;
35 use str::{self, FromStr, Utf8Error, Chars};
39 /// A UTF-8 encoded, growable string.
41 /// The `String` type is the most common string type that has ownership over the
42 /// contents of the string. It has a close relationship with its borrowed
43 /// counterpart, the primitive [`str`].
45 /// [`str`]: ../primitive.str.html
49 /// You can create a `String` from a literal string with `String::from`:
52 /// let hello = String::from("Hello, world!");
55 /// You can append a [`char`] to a `String` with the [`push()`] method, and
56 /// append a [`&str`] with the [`push_str()`] method:
59 /// let mut hello = String::from("Hello, ");
62 /// hello.push_str("orld!");
65 /// [`char`]: ../primitive.char.html
66 /// [`push()`]: #method.push
67 /// [`push_str()`]: #method.push_str
69 /// If you have a vector of UTF-8 bytes, you can create a `String` from it with
70 /// the [`from_utf8()`] method:
73 /// // some bytes, in a vector
74 /// let sparkle_heart = vec![240, 159, 146, 150];
76 /// // We know these bytes are valid, so we'll use `unwrap()`.
77 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
79 /// assert_eq!("💖", sparkle_heart);
82 /// [`from_utf8()`]: #method.from_utf8
86 /// `String`s are always valid UTF-8. This has a few implications, the first of
87 /// which is that if you need a non-UTF-8 string, consider [`OsString`]. It is
88 /// similar, but without the UTF-8 constraint. The second implication is that
89 /// you cannot index into a `String`:
94 /// println!("The first letter of s is {}", s[0]); // ERROR!!!
97 /// [`OsString`]: ../ffi/struct.OsString.html
99 /// Indexing is intended to be a constant-time operation, but UTF-8 encoding
100 /// does not allow us to do this. Furtheremore, it's not clear what sort of
101 /// thing the index should return: a byte, a codepoint, or a grapheme cluster.
102 /// The [`as_bytes()`] and [`chars()`] methods return iterators over the first
103 /// two, respectively.
105 /// [`as_bytes()`]: #method.as_bytes
106 /// [`chars()`]: #method.chars
110 /// `String`s implement [`Deref`]`<Target=str>`, and so inherit all of [`str`]'s
111 /// methods. In addition, this means that you can pass a `String` to any
112 /// function which takes a [`&str`] by using an ampersand (`&`):
115 /// fn takes_str(s: &str) { }
117 /// let s = String::from("Hello");
122 /// [`&str`]: ../primitive.str.html
123 /// [`Deref`]: ../ops/trait.Deref.html
125 /// This will create a [`&str`] from the `String` and pass it in. This
126 /// conversion is very inexpensive, and so generally, functions will accept
127 /// [`&str`]s as arguments unless they need a `String` for some specific reason.
132 /// A `String` is made up of three components: a pointer to some bytes, a
133 /// length, and a capacity. The pointer points to an internal buffer `String`
134 /// uses to store its data. The length is the number of bytes currently stored
135 /// in the buffer, and the capacity is the size of the buffer in bytes. As such,
136 /// the length will always be less than or equal to the capacity.
138 /// This buffer is always stored on the heap.
140 /// You can look at these with the [`as_ptr()`], [`len()`], and [`capacity()`]
146 /// let story = String::from("Once upon a time...");
148 /// let ptr = story.as_ptr();
149 /// let len = story.len();
150 /// let capacity = story.capacity();
152 /// // story has thirteen bytes
153 /// assert_eq!(19, len);
155 /// // Now that we have our parts, we throw the story away.
156 /// mem::forget(story);
158 /// // We can re-build a String out of ptr, len, and capacity. This is all
159 /// // unsafe becuase we are responsible for making sure the components are
161 /// let s = unsafe { String::from_raw_parts(ptr as *mut _, len, capacity) } ;
163 /// assert_eq!(String::from("Once upon a time..."), s);
166 /// [`as_ptr()`]: #method.as_ptr
167 /// [`len()`]: #method.len
168 /// [`capacity()`]: #method.capacity
170 /// If a `String` has enough capacity, adding elements to it will not
171 /// re-allocate. For example, consider this program:
174 /// let mut s = String::new();
176 /// println!("{}", s.capacity());
179 /// s.push_str("hello");
180 /// println!("{}", s.capacity());
184 /// This will output the following:
195 /// At first, we have no memory allocated at all, but as we append to the
196 /// string, it increases its capacity appropriately. If we instead use the
197 /// [`with_capacity()`] method to allocate the correct capacity initially:
200 /// let mut s = String::with_capacity(25);
202 /// println!("{}", s.capacity());
205 /// s.push_str("hello");
206 /// println!("{}", s.capacity());
210 /// [`with_capacity()`]: #method.with_capacity
212 /// We end up with a different output:
223 /// Here, there's no need to allocate more memory inside the loop.
224 #[derive(PartialOrd, Eq, Ord)]
225 #[stable(feature = "rust1", since = "1.0.0")]
230 /// A possible error value when converting a `String` from a UTF-8 byte vector.
232 /// This type is the error type for the [`from_utf8()`] method on [`String`]. It
233 /// is designed in such a way to carefully avoid reallocations: the
234 /// [`into_bytes()`] method will give back the byte vector that was used in the
235 /// conversion attempt.
237 /// [`from_utf8()`]: struct.String.html#method.from_utf8
238 /// [`String`]: struct.String.html
239 /// [`into_bytes()`]: struct.FromUtf8Error.html#method.into_bytes
241 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
242 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
243 /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
244 /// through the [`utf8_error()`] method.
246 /// [`Utf8Error`]: ../str/struct.Utf8Error.html
247 /// [`std::str`]: ../str/index.html
248 /// [`u8`]: ../primitive.u8.html
249 /// [`&str`]: ../primitive.str.html
250 /// [`utf8_error()`]: #method.utf8_error
257 /// // some invalid bytes, in a vector
258 /// let bytes = vec![0, 159];
260 /// let value = String::from_utf8(bytes);
262 /// assert!(value.is_err());
263 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
265 #[stable(feature = "rust1", since = "1.0.0")]
267 pub struct FromUtf8Error {
272 /// A possible error value when converting a `String` from a UTF-16 byte slice.
274 /// This type is the error type for the [`from_utf16()`] method on [`String`].
276 /// [`from_utf16()`]: struct.String.html#method.from_utf16
277 /// [`String`]: struct.String.html
284 /// // 𝄞mu<invalid>ic
285 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
286 /// 0xD800, 0x0069, 0x0063];
288 /// assert!(String::from_utf16(v).is_err());
290 #[stable(feature = "rust1", since = "1.0.0")]
292 pub struct FromUtf16Error(());
295 /// Creates a new empty `String`.
297 /// Given that the `String` is empty, this will not allocate any initial
298 /// buffer. While that means that this initial operation is very
299 /// inexpensive, but may cause excessive allocation later, when you add
300 /// data. If you have an idea of how much data the `String` will hold,
301 /// consider the [`with_capacity()`] method to prevent excessive
304 /// [`with_capacity()`]: #method.with_capacity
311 /// let s = String::new();
314 #[stable(feature = "rust1", since = "1.0.0")]
315 pub fn new() -> String {
316 String { vec: Vec::new() }
319 /// Creates a new empty `String` with a particular capacity.
321 /// `String`s have an internal buffer to hold their data. The capacity is
322 /// the length of that buffer, and can be queried with the [`capacity()`]
323 /// method. This method creates an empty `String`, but one with an initial
324 /// buffer that can hold `capacity` bytes. This is useful when you may be
325 /// appending a bunch of data to the `String`, reducing the number of
326 /// reallocations it needs to do.
328 /// [`capacity()`]: #method.capacity
330 /// If the given capacity is `0`, no allocation will occur, and this method
331 /// is identical to the [`new()`] method.
333 /// [`new()`]: #method.new
340 /// let mut s = String::with_capacity(10);
342 /// // The String contains no chars, even though it has capacity for more
343 /// assert_eq!(s.len(), 0);
345 /// // These are all done without reallocating...
346 /// let cap = s.capacity();
351 /// assert_eq!(s.capacity(), cap);
353 /// // ...but this may make the vector reallocate
357 #[stable(feature = "rust1", since = "1.0.0")]
358 pub fn with_capacity(capacity: usize) -> String {
359 String { vec: Vec::with_capacity(capacity) }
362 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
363 // required for this method definition, is not available. Since we don't
364 // require this method for testing purposes, I'll just stub it
365 // NB see the slice::hack module in slice.rs for more information
368 pub fn from_str(_: &str) -> String {
369 panic!("not available with cfg(test)");
372 /// Converts a vector of bytes to a `String`.
374 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a vector of bytes
375 /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
376 /// two. Not all byte slices are valid `String`s, however: `String`
377 /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
378 /// the bytes are valid UTF-8, and then does the conversion.
380 /// [`&str`]: ../primitive.str.html
381 /// [`u8`]: ../primitive.u8.html
382 /// [`Vec<u8>`]: ../vec/struct.Vec.html
384 /// If you are sure that the byte slice is valid UTF-8, and you don't want
385 /// to incur the overhead of the validity check, there is an unsafe version
386 /// of this function, [`from_utf8_unchecked()`], which has the same behavior
387 /// but skips the check.
389 /// [`from_utf8_unchecked()`]: struct.String.html#method.from_utf8_unchecked
391 /// This method will take care to not copy the vector, for efficiency's
394 /// If you need a `&str` instead of a `String`, consider
395 /// [`str::from_utf8()`].
397 /// [`str::from_utf8()`]: ../str/fn.from_utf8.html
401 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
402 /// provided bytes are not UTF-8. The vector you moved in is also included.
409 /// // some bytes, in a vector
410 /// let sparkle_heart = vec![240, 159, 146, 150];
412 /// // We know these bytes are valid, so we'll use `unwrap()`.
413 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
415 /// assert_eq!("💖", sparkle_heart);
421 /// // some invalid bytes, in a vector
422 /// let sparkle_heart = vec![0, 159, 146, 150];
424 /// assert!(String::from_utf8(sparkle_heart).is_err());
427 /// See the docs for [`FromUtf8Error`] for more details on what you can do
430 /// [`FromUtf8Error`]: struct.FromUtf8Error.html
432 #[stable(feature = "rust1", since = "1.0.0")]
433 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
434 match str::from_utf8(&vec) {
435 Ok(..) => Ok(String { vec: vec }),
445 /// Converts a slice of bytes to a `String`, including invalid characters.
447 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a slice of
448 /// bytes ([`&[u8]`][byteslice]) is made of bytes, so this function converts between
449 /// the two. Not all byte slices are valid string slices, however: [`&str`]
450 /// requires that it is valid UTF-8. During this conversion,
451 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
452 /// `U+FFFD REPLACEMENT CHARACTER`, which looks like this: �
454 /// [`&str`]: ../primitive.str.html
455 /// [`u8`]: ../primitive.u8.html
456 /// [byteslice]: ../primitive.slice.html
458 /// If you are sure that the byte slice is valid UTF-8, and you don't want
459 /// to incur the overhead of the conversion, there is an unsafe version
460 /// of this function, [`from_utf8_unchecked()`], which has the same behavior
461 /// but skips the checks.
463 /// [`from_utf8_unchecked()`]: struct.String.html#method.from_utf8_unchecked
465 /// If you need a [`&str`] instead of a `String`, consider
466 /// [`str::from_utf8()`].
468 /// [`str::from_utf8()`]: ../str/fn.from_utf8.html
475 /// // some bytes, in a vector
476 /// let sparkle_heart = vec![240, 159, 146, 150];
478 /// // We know these bytes are valid, so we'll use `unwrap()`.
479 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
481 /// assert_eq!("💖", sparkle_heart);
487 /// // some invalid bytes
488 /// let input = b"Hello \xF0\x90\x80World";
489 /// let output = String::from_utf8_lossy(input);
491 /// assert_eq!("Hello �World", output);
493 #[stable(feature = "rust1", since = "1.0.0")]
494 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
496 match str::from_utf8(v) {
497 Ok(s) => return Cow::Borrowed(s),
498 Err(e) => i = e.valid_up_to(),
501 const TAG_CONT_U8: u8 = 128;
502 const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
504 fn unsafe_get(xs: &[u8], i: usize) -> u8 {
505 unsafe { *xs.get_unchecked(i) }
507 fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 {
515 let mut res = String::with_capacity(total);
518 unsafe { res.as_mut_vec().extend_from_slice(&v[..i]) };
521 // subseqidx is the index of the first byte of the subsequence we're
522 // looking at. It's used to copy a bunch of contiguous good codepoints
523 // at once instead of copying them one by one.
524 let mut subseqidx = i;
528 let byte = unsafe_get(v, i);
531 macro_rules! error { () => ({
534 res.as_mut_vec().extend_from_slice(&v[subseqidx..i_]);
537 res.as_mut_vec().extend_from_slice(REPLACEMENT);
542 // subseqidx handles this
544 let w = unicode_str::utf8_char_width(byte);
548 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
555 match (byte, safe_get(v, i, total)) {
556 (0xE0, 0xA0...0xBF) => (),
557 (0xE1...0xEC, 0x80...0xBF) => (),
558 (0xED, 0x80...0x9F) => (),
559 (0xEE...0xEF, 0x80...0xBF) => (),
566 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
573 match (byte, safe_get(v, i, total)) {
574 (0xF0, 0x90...0xBF) => (),
575 (0xF1...0xF3, 0x80...0xBF) => (),
576 (0xF4, 0x80...0x8F) => (),
583 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
588 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
601 if subseqidx < total {
602 unsafe { res.as_mut_vec().extend_from_slice(&v[subseqidx..total]) };
607 /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
608 /// if `v` contains any invalid data.
616 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
617 /// 0x0073, 0x0069, 0x0063];
618 /// assert_eq!(String::from("𝄞music"),
619 /// String::from_utf16(v).unwrap());
621 /// // 𝄞mu<invalid>ic
622 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
623 /// 0xD800, 0x0069, 0x0063];
624 /// assert!(String::from_utf16(v).is_err());
626 #[stable(feature = "rust1", since = "1.0.0")]
627 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
628 decode_utf16(v.iter().cloned()).collect::<Result<_, _>>().map_err(|_| FromUtf16Error(()))
631 /// Decode a UTF-16 encoded vector `v` into a string, replacing
632 /// invalid data with the replacement character (U+FFFD).
639 /// // 𝄞mus<invalid>ic<invalid>
640 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
641 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
644 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
645 /// String::from_utf16_lossy(v));
648 #[stable(feature = "rust1", since = "1.0.0")]
649 pub fn from_utf16_lossy(v: &[u16]) -> String {
650 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
653 /// Creates a new `String` from a length, capacity, and pointer.
657 /// This is highly unsafe, due to the number of invariants that aren't
660 /// * The memory at `ptr` needs to have been previously allocated by the
661 /// same allocator the standard library uses.
662 /// * `length` needs to be less than or equal to `capacity`.
663 /// * `capacity` needs to be the correct value.
665 /// Violating these may cause problems like corrupting the allocator's
666 /// internal datastructures.
676 /// let s = String::from("hello");
677 /// let ptr = s.as_ptr();
678 /// let len = s.len();
679 /// let capacity = s.capacity();
683 /// let s = String::from_raw_parts(ptr as *mut _, len, capacity);
685 /// assert_eq!(String::from("hello"), s);
689 #[stable(feature = "rust1", since = "1.0.0")]
690 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
691 String { vec: Vec::from_raw_parts(buf, length, capacity) }
694 /// Converts a vector of bytes to a `String` without checking that the
695 /// string contains valid UTF-8.
697 /// See the safe version, [`from_utf8()`], for more details.
699 /// [`from_utf8()`]: struct.String.html#method.from_utf8
703 /// This function is unsafe because it does not check that the bytes passed
704 /// to it are valid UTF-8. If this constraint is violated, it may cause
705 /// memory unsafety issues with future users of the `String`, as the rest of
706 /// the standard library assumes that `String`s are valid UTF-8.
713 /// // some bytes, in a vector
714 /// let sparkle_heart = vec![240, 159, 146, 150];
716 /// let sparkle_heart = unsafe {
717 /// String::from_utf8_unchecked(sparkle_heart)
720 /// assert_eq!("💖", sparkle_heart);
723 #[stable(feature = "rust1", since = "1.0.0")]
724 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
725 String { vec: bytes }
728 /// Converts a `String` into a byte vector.
730 /// This consumes the `String`, so we do not need to copy its contents.
737 /// let s = String::from("hello");
738 /// let bytes = s.into_bytes();
740 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
743 #[stable(feature = "rust1", since = "1.0.0")]
744 pub fn into_bytes(self) -> Vec<u8> {
748 /// Extracts a string slice containing the entire string.
750 #[unstable(feature = "convert",
751 reason = "waiting on RFC revision",
753 pub fn as_str(&self) -> &str {
757 /// Appends a given string slice onto the end of this `String`.
764 /// let mut s = String::from("foo");
766 /// s.push_str("bar");
768 /// assert_eq!("foobar", s);
771 #[stable(feature = "rust1", since = "1.0.0")]
772 pub fn push_str(&mut self, string: &str) {
773 self.vec.extend_from_slice(string.as_bytes())
776 /// Returns this `String`'s capacity, in bytes.
783 /// let s = String::with_capacity(10);
785 /// assert!(s.capacity() >= 10);
788 #[stable(feature = "rust1", since = "1.0.0")]
789 pub fn capacity(&self) -> usize {
793 /// Ensures that this `String`'s capacity is at least `additional` bytes
794 /// larger than its length.
796 /// The capacity may be increased by more than `additional` bytes if it
797 /// chooses, to prevent frequent reallocations.
799 /// If you do not want this "at least" behavior, see the [`reserve_exact()`]
802 /// [`reserve_exact()`]: #method.reserve_exact
806 /// Panics if the new capacity overflows `usize`.
813 /// let mut s = String::new();
817 /// assert!(s.capacity() >= 10);
820 /// This may not actually increase the capacity:
823 /// let mut s = String::with_capacity(10);
827 /// // s now has a length of 2 and a capacity of 10
828 /// assert_eq!(2, s.len());
829 /// assert_eq!(10, s.capacity());
831 /// // Since we already have an extra 8 capacity, calling this...
834 /// // ... doesn't actually increase.
835 /// assert_eq!(10, s.capacity());
838 #[stable(feature = "rust1", since = "1.0.0")]
839 pub fn reserve(&mut self, additional: usize) {
840 self.vec.reserve(additional)
843 /// Ensures that this `String`'s capacity is `additional` bytes
844 /// larger than its length.
846 /// Consider using the [`reserve()`] method unless you absolutely know
847 /// better than the allocator.
849 /// [`reserve()`]: #method.reserve
853 /// Panics if the new capacity overflows `usize`.
860 /// let mut s = String::new();
862 /// s.reserve_exact(10);
864 /// assert!(s.capacity() >= 10);
867 /// This may not actually increase the capacity:
870 /// let mut s = String::with_capacity(10);
874 /// // s now has a length of 2 and a capacity of 10
875 /// assert_eq!(2, s.len());
876 /// assert_eq!(10, s.capacity());
878 /// // Since we already have an extra 8 capacity, calling this...
879 /// s.reserve_exact(8);
881 /// // ... doesn't actually increase.
882 /// assert_eq!(10, s.capacity());
885 #[stable(feature = "rust1", since = "1.0.0")]
886 pub fn reserve_exact(&mut self, additional: usize) {
887 self.vec.reserve_exact(additional)
890 /// Shrinks the capacity of this `String` to match its length.
897 /// let mut s = String::from("foo");
900 /// assert!(s.capacity() >= 100);
902 /// s.shrink_to_fit();
903 /// assert_eq!(3, s.capacity());
906 #[stable(feature = "rust1", since = "1.0.0")]
907 pub fn shrink_to_fit(&mut self) {
908 self.vec.shrink_to_fit()
911 /// Appends the given `char` to the end of this `String`.
918 /// let mut s = String::from("abc");
924 /// assert_eq!("abc123", s);
927 #[stable(feature = "rust1", since = "1.0.0")]
928 pub fn push(&mut self, ch: char) {
929 match ch.len_utf8() {
930 1 => self.vec.push(ch as u8),
932 let cur_len = self.len();
933 // This may use up to 4 bytes.
934 self.vec.reserve(ch_len);
937 // Attempt to not use an intermediate buffer by just pushing bytes
938 // directly onto this string.
939 let slice = slice::from_raw_parts_mut(self.vec
941 .offset(cur_len as isize),
943 let used = ch.encode_utf8(slice).unwrap_or(0);
944 self.vec.set_len(cur_len + used);
950 /// Returns a byte slice of this `String`'s contents.
957 /// let s = String::from("hello");
959 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
962 #[stable(feature = "rust1", since = "1.0.0")]
963 pub fn as_bytes(&self) -> &[u8] {
967 /// Shortens this `String` to the specified length.
971 /// Panics if `new_len` > current length, or if `new_len` does not lie on a
972 /// [`char`] boundary.
974 /// [`char`]: ../primitive.char.html
981 /// let mut s = String::from("hello");
985 /// assert_eq!("he", s);
988 #[stable(feature = "rust1", since = "1.0.0")]
989 pub fn truncate(&mut self, new_len: usize) {
990 assert!(self.is_char_boundary(new_len));
991 self.vec.truncate(new_len)
994 /// Removes the last character from the string buffer and returns it.
996 /// Returns `None` if this `String` is empty.
1003 /// let mut s = String::from("foo");
1005 /// assert_eq!(s.pop(), Some('o'));
1006 /// assert_eq!(s.pop(), Some('o'));
1007 /// assert_eq!(s.pop(), Some('f'));
1009 /// assert_eq!(s.pop(), None);
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 pub fn pop(&mut self) -> Option<char> {
1014 let len = self.len();
1019 let ch = self.char_at_reverse(len);
1021 self.vec.set_len(len - ch.len_utf8());
1026 /// Removes a `char` from this `String` at a byte position and returns it.
1028 /// This is an `O(n)` operation, as it requires copying every element in the
1033 /// Panics if `idx` is larger than or equal to the `String`'s length,
1034 /// or if it does not lie on a [`char`] boundary.
1036 /// [`char`]: ../primitive.char.html
1043 /// let mut s = String::from("foo");
1045 /// assert_eq!(s.remove(0), 'f');
1046 /// assert_eq!(s.remove(1), 'o');
1047 /// assert_eq!(s.remove(0), 'o');
1050 #[stable(feature = "rust1", since = "1.0.0")]
1051 pub fn remove(&mut self, idx: usize) -> char {
1052 let len = self.len();
1055 let ch = self.char_at(idx);
1056 let next = idx + ch.len_utf8();
1058 ptr::copy(self.vec.as_ptr().offset(next as isize),
1059 self.vec.as_mut_ptr().offset(idx as isize),
1061 self.vec.set_len(len - (next - idx));
1066 /// Inserts a character into this `String` at a byte position.
1068 /// This is an `O(n)` operation as it requires copying every element in the
1073 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1074 /// lie on a [`char`] boundary.
1076 /// [`char`]: ../primitive.char.html
1083 /// let mut s = String::with_capacity(3);
1085 /// s.insert(0, 'f');
1086 /// s.insert(1, 'o');
1087 /// s.insert(2, 'o');
1089 /// assert_eq!("foo", s);
1092 #[stable(feature = "rust1", since = "1.0.0")]
1093 pub fn insert(&mut self, idx: usize, ch: char) {
1094 let len = self.len();
1095 assert!(idx <= len);
1096 assert!(self.is_char_boundary(idx));
1097 self.vec.reserve(4);
1098 let mut bits = [0; 4];
1099 let amt = ch.encode_utf8(&mut bits).unwrap();
1102 ptr::copy(self.vec.as_ptr().offset(idx as isize),
1103 self.vec.as_mut_ptr().offset((idx + amt) as isize),
1105 ptr::copy(bits.as_ptr(),
1106 self.vec.as_mut_ptr().offset(idx as isize),
1108 self.vec.set_len(len + amt);
1112 /// Returns a mutable reference to the contents of this `String`.
1116 /// This function is unsafe because it does not check that the bytes passed
1117 /// to it are valid UTF-8. If this constraint is violated, it may cause
1118 /// memory unsafety issues with future users of the `String`, as the rest of
1119 /// the standard library assumes that `String`s are valid UTF-8.
1126 /// let mut s = String::from("hello");
1129 /// let vec = s.as_mut_vec();
1130 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1134 /// assert_eq!(s, "olleh");
1137 #[stable(feature = "rust1", since = "1.0.0")]
1138 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1142 /// Returns the length of this `String`, in bytes.
1149 /// let a = String::from("foo");
1151 /// assert_eq!(a.len(), 3);
1154 #[stable(feature = "rust1", since = "1.0.0")]
1155 pub fn len(&self) -> usize {
1159 /// Returns `true` if this `String` has a length of zero.
1161 /// Returns `false` otherwise.
1168 /// let mut v = String::new();
1169 /// assert!(v.is_empty());
1172 /// assert!(!v.is_empty());
1175 #[stable(feature = "rust1", since = "1.0.0")]
1176 pub fn is_empty(&self) -> bool {
1180 /// Truncates this `String`, removing all contents.
1182 /// While this means the `String` will have a length of zero, it does not
1183 /// touch its capacity.
1190 /// let mut s = String::from("foo");
1194 /// assert!(s.is_empty());
1195 /// assert_eq!(0, s.len());
1196 /// assert_eq!(3, s.capacity());
1199 #[stable(feature = "rust1", since = "1.0.0")]
1200 pub fn clear(&mut self) {
1204 /// Create a draining iterator that removes the specified range in the string
1205 /// and yields the removed chars.
1207 /// Note: The element range is removed even if the iterator is not
1208 /// consumed until the end.
1212 /// Panics if the starting point or end point do not lie on a [`char`]
1213 /// boundary, or if they're out of bounds.
1215 /// [`char`]: ../primitive.char.html
1222 /// let mut s = String::from("α is alpha, β is beta");
1223 /// let beta_offset = s.find('β').unwrap_or(s.len());
1225 /// // Remove the range up until the β from the string
1226 /// let t: String = s.drain(..beta_offset).collect();
1227 /// assert_eq!(t, "α is alpha, ");
1228 /// assert_eq!(s, "β is beta");
1230 /// // A full range clears the string
1232 /// assert_eq!(s, "");
1234 #[stable(feature = "drain", since = "1.6.0")]
1235 pub fn drain<R>(&mut self, range: R) -> Drain
1236 where R: RangeArgument<usize>
1240 // The String version of Drain does not have the memory safety issues
1241 // of the vector version. The data is just plain bytes.
1242 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1243 // the removal will not happen.
1244 let len = self.len();
1245 let start = *range.start().unwrap_or(&0);
1246 let end = *range.end().unwrap_or(&len);
1248 // Take out two simultaneous borrows. The &mut String won't be accessed
1249 // until iteration is over, in Drop.
1250 let self_ptr = self as *mut _;
1251 // slicing does the appropriate bounds checks
1252 let chars_iter = self[start..end].chars();
1262 /// Converts this `String` into a `Box<str>`.
1264 /// This will drop any excess capacity.
1271 /// let s = String::from("hello");
1273 /// let b = s.into_boxed_str();
1275 #[stable(feature = "box_str", since = "1.4.0")]
1276 pub fn into_boxed_str(self) -> Box<str> {
1277 let slice = self.vec.into_boxed_slice();
1278 unsafe { mem::transmute::<Box<[u8]>, Box<str>>(slice) }
1282 impl FromUtf8Error {
1283 /// Returns the bytes that were attempted to convert to a `String`.
1285 /// This method is carefully constructed to avoid allocation. It will
1286 /// consume the error, moving out the bytes, so that a copy of the bytes
1287 /// does not need to be made.
1294 /// // some invalid bytes, in a vector
1295 /// let bytes = vec![0, 159];
1297 /// let value = String::from_utf8(bytes);
1299 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1301 #[stable(feature = "rust1", since = "1.0.0")]
1302 pub fn into_bytes(self) -> Vec<u8> {
1306 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1308 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1309 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1310 /// an analogue to `FromUtf8Error`. See its documentation for more details
1313 /// [`Utf8Error`]: ../str/struct.Utf8Error.html
1314 /// [`std::str`]: ../str/index.html
1315 /// [`u8`]: ../primitive.u8.html
1316 /// [`&str`]: ../primitive.str.html
1323 /// // some invalid bytes, in a vector
1324 /// let bytes = vec![0, 159];
1326 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1328 /// // the first byte is invalid here
1329 /// assert_eq!(1, error.valid_up_to());
1331 #[stable(feature = "rust1", since = "1.0.0")]
1332 pub fn utf8_error(&self) -> Utf8Error {
1337 #[stable(feature = "rust1", since = "1.0.0")]
1338 impl fmt::Display for FromUtf8Error {
1339 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1340 fmt::Display::fmt(&self.error, f)
1344 #[stable(feature = "rust1", since = "1.0.0")]
1345 impl fmt::Display for FromUtf16Error {
1346 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1347 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1351 #[stable(feature = "rust1", since = "1.0.0")]
1352 impl Clone for String {
1353 fn clone(&self) -> Self {
1354 String { vec: self.vec.clone() }
1357 fn clone_from(&mut self, source: &Self) {
1358 self.vec.clone_from(&source.vec);
1362 #[stable(feature = "rust1", since = "1.0.0")]
1363 impl FromIterator<char> for String {
1364 fn from_iter<I: IntoIterator<Item = char>>(iterable: I) -> String {
1365 let mut buf = String::new();
1366 buf.extend(iterable);
1371 #[stable(feature = "rust1", since = "1.0.0")]
1372 impl<'a> FromIterator<&'a str> for String {
1373 fn from_iter<I: IntoIterator<Item = &'a str>>(iterable: I) -> String {
1374 let mut buf = String::new();
1375 buf.extend(iterable);
1380 #[stable(feature = "extend_string", since = "1.4.0")]
1381 impl FromIterator<String> for String {
1382 fn from_iter<I: IntoIterator<Item = String>>(iterable: I) -> String {
1383 let mut buf = String::new();
1384 buf.extend(iterable);
1389 #[stable(feature = "rust1", since = "1.0.0")]
1390 impl Extend<char> for String {
1391 fn extend<I: IntoIterator<Item = char>>(&mut self, iterable: I) {
1392 let iterator = iterable.into_iter();
1393 let (lower_bound, _) = iterator.size_hint();
1394 self.reserve(lower_bound);
1395 for ch in iterator {
1401 #[stable(feature = "extend_ref", since = "1.2.0")]
1402 impl<'a> Extend<&'a char> for String {
1403 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iterable: I) {
1404 self.extend(iterable.into_iter().cloned());
1408 #[stable(feature = "rust1", since = "1.0.0")]
1409 impl<'a> Extend<&'a str> for String {
1410 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iterable: I) {
1417 #[stable(feature = "extend_string", since = "1.4.0")]
1418 impl Extend<String> for String {
1419 fn extend<I: IntoIterator<Item = String>>(&mut self, iterable: I) {
1426 /// A convenience impl that delegates to the impl for `&str`
1427 #[unstable(feature = "pattern",
1428 reason = "API not fully fleshed out and ready to be stabilized",
1430 impl<'a, 'b> Pattern<'a> for &'b String {
1431 type Searcher = <&'b str as Pattern<'a>>::Searcher;
1433 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1434 self[..].into_searcher(haystack)
1438 fn is_contained_in(self, haystack: &'a str) -> bool {
1439 self[..].is_contained_in(haystack)
1443 fn is_prefix_of(self, haystack: &'a str) -> bool {
1444 self[..].is_prefix_of(haystack)
1448 #[stable(feature = "rust1", since = "1.0.0")]
1449 impl PartialEq for String {
1451 fn eq(&self, other: &String) -> bool {
1452 PartialEq::eq(&self[..], &other[..])
1455 fn ne(&self, other: &String) -> bool {
1456 PartialEq::ne(&self[..], &other[..])
1460 macro_rules! impl_eq {
1461 ($lhs:ty, $rhs: ty) => {
1462 #[stable(feature = "rust1", since = "1.0.0")]
1463 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1465 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1467 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1470 #[stable(feature = "rust1", since = "1.0.0")]
1471 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1473 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1475 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1481 impl_eq! { String, str }
1482 impl_eq! { String, &'a str }
1483 impl_eq! { Cow<'a, str>, str }
1484 impl_eq! { Cow<'a, str>, &'b str }
1485 impl_eq! { Cow<'a, str>, String }
1487 #[stable(feature = "rust1", since = "1.0.0")]
1488 impl Default for String {
1490 fn default() -> String {
1495 #[stable(feature = "rust1", since = "1.0.0")]
1496 impl fmt::Display for String {
1498 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1499 fmt::Display::fmt(&**self, f)
1503 #[stable(feature = "rust1", since = "1.0.0")]
1504 impl fmt::Debug for String {
1506 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1507 fmt::Debug::fmt(&**self, f)
1511 #[stable(feature = "rust1", since = "1.0.0")]
1512 impl hash::Hash for String {
1514 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1515 (**self).hash(hasher)
1519 #[stable(feature = "rust1", since = "1.0.0")]
1520 impl<'a> Add<&'a str> for String {
1521 type Output = String;
1524 fn add(mut self, other: &str) -> String {
1525 self.push_str(other);
1530 #[stable(feature = "rust1", since = "1.0.0")]
1531 impl ops::Index<ops::Range<usize>> for String {
1535 fn index(&self, index: ops::Range<usize>) -> &str {
1539 #[stable(feature = "rust1", since = "1.0.0")]
1540 impl ops::Index<ops::RangeTo<usize>> for String {
1544 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1548 #[stable(feature = "rust1", since = "1.0.0")]
1549 impl ops::Index<ops::RangeFrom<usize>> for String {
1553 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1557 #[stable(feature = "rust1", since = "1.0.0")]
1558 impl ops::Index<ops::RangeFull> for String {
1562 fn index(&self, _index: ops::RangeFull) -> &str {
1563 unsafe { str::from_utf8_unchecked(&self.vec) }
1567 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1568 impl ops::IndexMut<ops::Range<usize>> for String {
1570 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1571 &mut self[..][index]
1574 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1575 impl ops::IndexMut<ops::RangeTo<usize>> for String {
1577 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1578 &mut self[..][index]
1581 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1582 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
1584 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1585 &mut self[..][index]
1588 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1589 impl ops::IndexMut<ops::RangeFull> for String {
1591 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1592 unsafe { mem::transmute(&mut *self.vec) }
1596 #[stable(feature = "rust1", since = "1.0.0")]
1597 impl ops::Deref for String {
1601 fn deref(&self) -> &str {
1602 unsafe { str::from_utf8_unchecked(&self.vec) }
1606 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1607 impl ops::DerefMut for String {
1609 fn deref_mut(&mut self) -> &mut str {
1610 unsafe { mem::transmute(&mut *self.vec) }
1614 /// An error when parsing a `String`.
1616 /// This `enum` is slightly awkward: it will never actually exist. This error is
1617 /// part of the type signature of the implementation of [`FromStr`] on
1618 /// [`String`]. The return type of [`from_str()`], requires that an error be
1619 /// defined, but, given that a [`String`] can always be made into a new
1620 /// [`String`] without error, this type will never actually be returned. As
1621 /// such, it is only here to satisfy said signature, and is useless otherwise.
1623 /// [`FromStr`]: ../str/trait.FromStr.html
1624 /// [`String`]: struct.String.html
1625 /// [`from_str()`]: ../str/trait.FromStr.html#tymethod.from_str
1626 #[stable(feature = "str_parse_error", since = "1.5.0")]
1628 pub enum ParseError {}
1630 #[stable(feature = "rust1", since = "1.0.0")]
1631 impl FromStr for String {
1632 type Err = ParseError;
1634 fn from_str(s: &str) -> Result<String, ParseError> {
1639 #[stable(feature = "str_parse_error", since = "1.5.0")]
1640 impl Clone for ParseError {
1641 fn clone(&self) -> ParseError {
1646 #[stable(feature = "str_parse_error", since = "1.5.0")]
1647 impl fmt::Debug for ParseError {
1648 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1653 #[stable(feature = "str_parse_error", since = "1.5.0")]
1654 impl PartialEq for ParseError {
1655 fn eq(&self, _: &ParseError) -> bool {
1660 #[stable(feature = "str_parse_error", since = "1.5.0")]
1661 impl Eq for ParseError {}
1663 /// A trait for converting a value to a `String`.
1665 /// This trait is automatically implemented for any type which implements the
1666 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
1667 /// [`Display`] should be implemented instead, and you get the `ToString`
1668 /// implementation for free.
1670 /// [`Display`]: ../fmt/trait.Display.html
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 pub trait ToString {
1673 /// Converts the given value to a `String`.
1681 /// let five = String::from("5");
1683 /// assert_eq!(five, i.to_string());
1685 #[stable(feature = "rust1", since = "1.0.0")]
1686 fn to_string(&self) -> String;
1689 #[stable(feature = "rust1", since = "1.0.0")]
1690 impl<T: fmt::Display + ?Sized> ToString for T {
1692 fn to_string(&self) -> String {
1693 use core::fmt::Write;
1694 let mut buf = String::new();
1695 let _ = buf.write_fmt(format_args!("{}", self));
1696 buf.shrink_to_fit();
1701 #[stable(feature = "rust1", since = "1.0.0")]
1702 impl AsRef<str> for String {
1704 fn as_ref(&self) -> &str {
1709 #[stable(feature = "rust1", since = "1.0.0")]
1710 impl AsRef<[u8]> for String {
1712 fn as_ref(&self) -> &[u8] {
1717 #[stable(feature = "rust1", since = "1.0.0")]
1718 impl<'a> From<&'a str> for String {
1721 fn from(s: &'a str) -> String {
1722 String { vec: <[_]>::to_vec(s.as_bytes()) }
1725 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1726 // required for this method definition, is not available. Since we don't
1727 // require this method for testing purposes, I'll just stub it
1728 // NB see the slice::hack module in slice.rs for more information
1731 fn from(_: &str) -> String {
1732 panic!("not available with cfg(test)");
1736 #[stable(feature = "rust1", since = "1.0.0")]
1737 impl<'a> From<&'a str> for Cow<'a, str> {
1739 fn from(s: &'a str) -> Cow<'a, str> {
1744 #[stable(feature = "rust1", since = "1.0.0")]
1745 impl<'a> From<String> for Cow<'a, str> {
1747 fn from(s: String) -> Cow<'a, str> {
1752 #[stable(feature = "rust1", since = "1.0.0")]
1753 impl Into<Vec<u8>> for String {
1754 fn into(self) -> Vec<u8> {
1759 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`",
1761 impl IntoCow<'static, str> for String {
1763 fn into_cow(self) -> Cow<'static, str> {
1768 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`",
1770 impl<'a> IntoCow<'a, str> for &'a str {
1772 fn into_cow(self) -> Cow<'a, str> {
1777 #[stable(feature = "rust1", since = "1.0.0")]
1778 impl fmt::Write for String {
1780 fn write_str(&mut self, s: &str) -> fmt::Result {
1786 fn write_char(&mut self, c: char) -> fmt::Result {
1792 /// A draining iterator for `String`.
1793 #[stable(feature = "drain", since = "1.6.0")]
1794 pub struct Drain<'a> {
1795 /// Will be used as &'a mut String in the destructor
1796 string: *mut String,
1797 /// Start of part to remove
1799 /// End of part to remove
1801 /// Current remaining range to remove
1805 #[stable(feature = "drain", since = "1.6.0")]
1806 unsafe impl<'a> Sync for Drain<'a> {}
1807 #[stable(feature = "drain", since = "1.6.0")]
1808 unsafe impl<'a> Send for Drain<'a> {}
1810 #[stable(feature = "drain", since = "1.6.0")]
1811 impl<'a> Drop for Drain<'a> {
1812 fn drop(&mut self) {
1814 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
1815 // panic code being inserted again.
1816 let self_vec = (*self.string).as_mut_vec();
1817 if self.start <= self.end && self.end <= self_vec.len() {
1818 self_vec.drain(self.start..self.end);
1824 #[stable(feature = "drain", since = "1.6.0")]
1825 impl<'a> Iterator for Drain<'a> {
1829 fn next(&mut self) -> Option<char> {
1833 fn size_hint(&self) -> (usize, Option<usize>) {
1834 self.iter.size_hint()
1838 #[stable(feature = "drain", since = "1.6.0")]
1839 impl<'a> DoubleEndedIterator for Drain<'a> {
1841 fn next_back(&mut self) -> Option<char> {
1842 self.iter.next_back()