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 /// [`push()`]: #method.push
66 /// [`push_str()`]: #method.push_str
68 /// If you have a vector of UTF-8 bytes, you can create a `String` from it with
69 /// the [`from_utf8()`] method:
72 /// // some bytes, in a vector
73 /// let sparkle_heart = vec![240, 159, 146, 150];
75 /// // We know these bytes are valid, so we'll use `unwrap()`.
76 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
78 /// assert_eq!("💖", sparkle_heart);
81 /// [`from_utf8()`]: #method.from_utf8
85 /// `String`s are always valid UTF-8. This has a few implications, the first of
86 /// which is that if you need a non-UTF-8 string, consider [`OsString`]. It is
87 /// similar, but without the UTF-8 constraint. The second implication is that
88 /// you cannot index into a `String`:
93 /// println!("The first letter of s is {}", s[0]); // ERROR!!!
96 /// [`OsString`]: ../ffi/struct.OsString.html
98 /// Indexing is intended to be a constant-time operation, but UTF-8 encoding
99 /// does not allow us to do this. Furtheremore, it's not clear what sort of
100 /// thing the index should return: a byte, a codepoint, or a grapheme cluster.
101 /// The [`as_bytes()`] and [`chars()`] methods return iterators over the first
102 /// two, respectively.
104 /// [`as_bytes()`]: #method.as_bytes
105 /// [`chars()`]: #method.chars
109 /// `String`s implement [`Deref`]`<Target=str>`, and so inherit all of [`str`]'s
110 /// methods. In addition, this means that you can pass a `String` to any
111 /// function which takes a [`&str`] by using an ampersand (`&`):
114 /// fn takes_str(s: &str) { }
116 /// let s = String::from("Hello");
121 /// [`&str`]: ../primitive.str.html
122 /// [`Deref`]: ../ops/trait.Deref.html
124 /// This will create a [`&str`] from the `String` and pass it in. This
125 /// conversion is very inexpensive, and so generally, functions will accept
126 /// [`&str`]s as arguments unless they need a `String` for some specific reason.
131 /// A `String` is made up of three components: a pointer to some bytes, a
132 /// length, and a capacity. The pointer points to an internal buffer `String`
133 /// uses to store its data. The length is the number of bytes currently stored
134 /// in the buffer, and the capacity is the size of the buffer in bytes. As such,
135 /// the length will always be less than or equal to the capacity.
137 /// This buffer is always stored on the heap.
139 /// You can look at these with the [`as_ptr()`], [`len()`], and [`capacity()`]
145 /// let story = String::from("Once upon a time...");
147 /// let ptr = story.as_ptr();
148 /// let len = story.len();
149 /// let capacity = story.capacity();
151 /// // story has thirteen bytes
152 /// assert_eq!(19, len);
154 /// // Now that we have our parts, we throw the story away.
155 /// mem::forget(story);
157 /// // We can re-build a String out of ptr, len, and capacity. This is all
158 /// // unsafe becuase we are responsible for making sure the components are
160 /// let s = unsafe { String::from_raw_parts(ptr as *mut _, len, capacity) } ;
162 /// assert_eq!(String::from("Once upon a time..."), s);
165 /// [`as_ptr()`]: #method.as_ptr
166 /// [`len()`]: # method.len
167 /// [`capacity()`]: # method.capacity
169 /// If a `String` has enough capacity, adding elements to it will not
170 /// re-allocate. For example, consider this program:
173 /// let mut s = String::new();
175 /// println!("{}", s.capacity());
178 /// s.push_str("hello");
179 /// println!("{}", s.capacity());
183 /// This will output the following:
194 /// At first, we have no memory allocated at all, but as we append to the
195 /// string, it increases its capacity appropriately. If we instead use the
196 /// [`with_capacity()`] method to allocate the correct capacity initially:
199 /// let mut s = String::with_capacity(25);
201 /// println!("{}", s.capacity());
204 /// s.push_str("hello");
205 /// println!("{}", s.capacity());
209 /// [`with_capacity()`]: #method.with_capacity
211 /// We end up with a different output:
222 /// Here, there's no need to allocate more memory inside the loop.
223 #[derive(PartialOrd, Eq, Ord)]
224 #[stable(feature = "rust1", since = "1.0.0")]
229 /// A possible error value when converting a `String` from a UTF-8 byte vector.
231 /// This type is the error type for the [`from_utf8()`] method on [`String`]. It
232 /// is designed in such a way to carefully avoid reallocations: the
233 /// [`into_bytes()`] method will give back the byte vector that was used in the
234 /// conversion attempt.
236 /// [`from_utf8()`]: struct.String.html#method.from_utf8
237 /// [`String`]: struct.String.html
238 /// [`into_bytes()`]: struct.FromUtf8Error.html#method.into_bytes
240 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
241 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
242 /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
243 /// through the [`utf8_error()`] method.
245 /// [`Utf8Error`]: ../str/struct.Utf8Error.html
246 /// [`std::str`]: ../str/index.html
247 /// [`u8`]: ../primitive.u8.html
248 /// [`&str`]: ../primitive.str.html
249 /// [`utf8_error()`]: #method.utf8_error
256 /// // some invalid bytes, in a vector
257 /// let bytes = vec![0, 159];
259 /// let value = String::from_utf8(bytes);
261 /// assert!(value.is_err());
262 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
264 #[stable(feature = "rust1", since = "1.0.0")]
266 pub struct FromUtf8Error {
271 /// A possible error value when converting a `String` from a UTF-16 byte slice.
273 /// This type is the error type for the [`from_utf16()`] method on [`String`].
275 /// [`from_utf16()`]: struct.String.html#method.from_utf16
276 /// [`String`]: struct.String.html
283 /// // 𝄞mu<invalid>ic
284 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
285 /// 0xD800, 0x0069, 0x0063];
287 /// assert!(String::from_utf16(v).is_err());
289 #[stable(feature = "rust1", since = "1.0.0")]
291 pub struct FromUtf16Error(());
294 /// Creates a new empty `String`.
296 /// Given that the `String` is empty, this will not allocate any initial
297 /// buffer. While that means that this initial operation is very
298 /// inexpensive, but may cause excessive allocation later, when you add
299 /// data. If you have an idea of how much data the `String` will hold,
300 /// consider the [`with_capacity()`] method to prevent excessive
303 /// [`with_capacity()`]: #method.with_capacity
310 /// let s = String::new();
313 #[stable(feature = "rust1", since = "1.0.0")]
314 pub fn new() -> String {
315 String { vec: Vec::new() }
318 /// Creates a new empty `String` with a particular capacity.
320 /// `String`s have an internal buffer to hold their data. The capacity is
321 /// the length of that buffer, and can be queried with the [`capacity()`]
322 /// method. This method creates an empty `String`, but one with an initial
323 /// buffer that can hold `capacity` bytes. This is useful when you may be
324 /// appending a bunch of data to the `String`, reducing the number of
325 /// reallocations it needs to do.
327 /// [`capacity()`]: #method.capacity
329 /// If the given capacity is `0`, no allocation will occur, and this method
330 /// is identical to the [`new()`] method.
332 /// [`new()`]: #method.new
339 /// let mut s = String::with_capacity(10);
341 /// // The String contains no chars, even though it has capacity for more
342 /// assert_eq!(s.len(), 0);
344 /// // These are all done without reallocating...
345 /// let cap = s.capacity();
350 /// assert_eq!(s.capacity(), cap);
352 /// // ...but this may make the vector reallocate
356 #[stable(feature = "rust1", since = "1.0.0")]
357 pub fn with_capacity(capacity: usize) -> String {
358 String { vec: Vec::with_capacity(capacity) }
361 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
362 // required for this method definition, is not available. Since we don't
363 // require this method for testing purposes, I'll just stub it
364 // NB see the slice::hack module in slice.rs for more information
367 pub fn from_str(_: &str) -> String {
368 panic!("not available with cfg(test)");
371 /// Converts a vector of bytes to a `String`.
373 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a vector of bytes
374 /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
375 /// two. Not all byte slices are valid `String`s, however: `String`
376 /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
377 /// the bytes are valid UTF-8, and then does the conversion.
379 /// [`&str`]: ../primitive.str.html
380 /// [`u8`]: ../primitive.u8.html
381 /// [`Vec<u8>`]: ../vec/struct.Vec.html
383 /// If you are sure that the byte slice is valid UTF-8, and you don't want
384 /// to incur the overhead of the validity check, there is an unsafe version
385 /// of this function, [`from_utf8_unchecked()`], which has the same behavior
386 /// but skips the check.
388 /// [`from_utf8_unchecked()`]: struct.String.html#method.from_utf8_unchecked
390 /// This method will take care to not copy the vector, for efficiency's
393 /// If you need a `&str` instead of a `String`, consider
394 /// [`str::from_utf8()`].
396 /// [`str::from_utf8()`]: ../str/fn.from_utf8.html
400 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
401 /// provided bytes are not UTF-8. The vector you moved in is also included.
408 /// // some bytes, in a vector
409 /// let sparkle_heart = vec![240, 159, 146, 150];
411 /// // We know these bytes are valid, so we'll use `unwrap()`.
412 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
414 /// assert_eq!("💖", sparkle_heart);
420 /// // some invalid bytes, in a vector
421 /// let sparkle_heart = vec![0, 159, 146, 150];
423 /// assert!(String::from_utf8(sparkle_heart).is_err());
426 /// See the docs for [`FromUtf8Error`] for more details on what you can do
429 /// [`FromUtf8Error`]: struct.FromUtf8Error.html
431 #[stable(feature = "rust1", since = "1.0.0")]
432 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
433 match str::from_utf8(&vec) {
434 Ok(..) => Ok(String { vec: vec }),
444 /// Converts a slice of bytes to a `String`, including invalid characters.
446 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a slice of
447 /// bytes ([`&[u8]`]) is made of bytes, so this function converts between
448 /// the two. Not all byte slices are valid string slices, however: [`&str`]
449 /// requires that it is valid UTF-8. During this conversion,
450 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
451 /// `U+FFFD REPLACEMENT CHARACTER`, which looks like this: �
453 /// [`&str`]: ../primitive.str.html
454 /// [`u8`]: ../primitive.u8.html
455 /// [`&[u8]`]: ../primitive.slice.html
457 /// If you are sure that the byte slice is valid UTF-8, and you don't want
458 /// to incur the overhead of the conversion, there is an unsafe version
459 /// of this function, [`from_utf8_unchecked()`], which has the same behavior
460 /// but skips the checks.
462 /// [`from_utf8_unchecked()`]: struct.String.html#method.from_utf8_unchecked
464 /// If you need a [`&str`] instead of a `String`, consider
465 /// [`str::from_utf8()`].
467 /// [`str::from_utf8()`]: ../str/fn.from_utf8.html
474 /// // some bytes, in a vector
475 /// let sparkle_heart = vec![240, 159, 146, 150];
477 /// // We know these bytes are valid, so we'll use `unwrap()`.
478 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
480 /// assert_eq!("💖", sparkle_heart);
486 /// // some invalid bytes
487 /// let input = b"Hello \xF0\x90\x80World";
488 /// let output = String::from_utf8_lossy(input);
490 /// assert_eq!("Hello �World", output);
492 #[stable(feature = "rust1", since = "1.0.0")]
493 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
495 match str::from_utf8(v) {
496 Ok(s) => return Cow::Borrowed(s),
497 Err(e) => i = e.valid_up_to(),
500 const TAG_CONT_U8: u8 = 128;
501 const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
503 fn unsafe_get(xs: &[u8], i: usize) -> u8 {
504 unsafe { *xs.get_unchecked(i) }
506 fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 {
514 let mut res = String::with_capacity(total);
517 unsafe { res.as_mut_vec().extend_from_slice(&v[..i]) };
520 // subseqidx is the index of the first byte of the subsequence we're
521 // looking at. It's used to copy a bunch of contiguous good codepoints
522 // at once instead of copying them one by one.
523 let mut subseqidx = i;
527 let byte = unsafe_get(v, i);
530 macro_rules! error { () => ({
533 res.as_mut_vec().extend_from_slice(&v[subseqidx..i_]);
536 res.as_mut_vec().extend_from_slice(REPLACEMENT);
541 // subseqidx handles this
543 let w = unicode_str::utf8_char_width(byte);
547 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
554 match (byte, safe_get(v, i, total)) {
555 (0xE0, 0xA0...0xBF) => (),
556 (0xE1...0xEC, 0x80...0xBF) => (),
557 (0xED, 0x80...0x9F) => (),
558 (0xEE...0xEF, 0x80...0xBF) => (),
565 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
572 match (byte, safe_get(v, i, total)) {
573 (0xF0, 0x90...0xBF) => (),
574 (0xF1...0xF3, 0x80...0xBF) => (),
575 (0xF4, 0x80...0x8F) => (),
582 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
587 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
600 if subseqidx < total {
601 unsafe { res.as_mut_vec().extend_from_slice(&v[subseqidx..total]) };
606 /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
607 /// if `v` contains any invalid data.
615 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
616 /// 0x0073, 0x0069, 0x0063];
617 /// assert_eq!(String::from("𝄞music"),
618 /// String::from_utf16(v).unwrap());
620 /// // 𝄞mu<invalid>ic
621 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
622 /// 0xD800, 0x0069, 0x0063];
623 /// assert!(String::from_utf16(v).is_err());
625 #[stable(feature = "rust1", since = "1.0.0")]
626 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
627 decode_utf16(v.iter().cloned()).collect::<Result<_, _>>().map_err(|_| FromUtf16Error(()))
630 /// Decode a UTF-16 encoded vector `v` into a string, replacing
631 /// invalid data with the replacement character (U+FFFD).
638 /// // 𝄞mus<invalid>ic<invalid>
639 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
640 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
643 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
644 /// String::from_utf16_lossy(v));
647 #[stable(feature = "rust1", since = "1.0.0")]
648 pub fn from_utf16_lossy(v: &[u16]) -> String {
649 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
652 /// Creates a new `String` from a length, capacity, and pointer.
656 /// This is highly unsafe, due to the number of invariants that aren't
659 /// * The memory at `ptr` needs to have been previously allocated by the
660 /// same allocator the standard library uses.
661 /// * `length` needs to be less than or equal to `capacity`.
662 /// * `capacity` needs to be the correct value.
664 /// Violating these may cause problems like corrupting the allocator's
665 /// internal datastructures.
675 /// let s = String::from("hello");
676 /// let ptr = s.as_ptr();
677 /// let len = s.len();
678 /// let capacity = s.capacity();
682 /// let s = String::from_raw_parts(ptr as *mut _, len, capacity);
684 /// assert_eq!(String::from("hello"), s);
688 #[stable(feature = "rust1", since = "1.0.0")]
689 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
690 String { vec: Vec::from_raw_parts(buf, length, capacity) }
693 /// Converts a vector of bytes to a `String` without checking that the
694 /// string contains valid UTF-8.
696 /// See the safe version, [`from_utf8()`], for more details.
698 /// [`from_utf8()`]: struct.String.html#method.from_utf8
702 /// This function is unsafe because it does not check that the bytes passed
703 /// to it are valid UTF-8. If this constraint is violated, it may cause
704 /// memory unsafety issues with future users of the `String`, as the rest of
705 /// the standard library assumes that `String`s are valid UTF-8.
712 /// // some bytes, in a vector
713 /// let sparkle_heart = vec![240, 159, 146, 150];
715 /// let sparkle_heart = unsafe {
716 /// String::from_utf8_unchecked(sparkle_heart)
719 /// assert_eq!("💖", sparkle_heart);
722 #[stable(feature = "rust1", since = "1.0.0")]
723 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
724 String { vec: bytes }
727 /// Converts a `String` into a byte vector.
729 /// This consumes the `String`, so we do not need to copy its contents.
736 /// let s = String::from("hello");
737 /// let bytes = s.into_bytes();
739 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
742 #[stable(feature = "rust1", since = "1.0.0")]
743 pub fn into_bytes(self) -> Vec<u8> {
747 /// Extracts a string slice containing the entire string.
749 #[unstable(feature = "convert",
750 reason = "waiting on RFC revision",
752 pub fn as_str(&self) -> &str {
756 /// Appends a given string slice onto the end of this `String`.
763 /// let mut s = String::from("foo");
765 /// s.push_str("bar");
767 /// assert_eq!("foobar", s);
770 #[stable(feature = "rust1", since = "1.0.0")]
771 pub fn push_str(&mut self, string: &str) {
772 self.vec.extend_from_slice(string.as_bytes())
775 /// Returns this `String`'s capacity, in bytes.
782 /// let s = String::with_capacity(10);
784 /// assert!(s.capacity() >= 10);
787 #[stable(feature = "rust1", since = "1.0.0")]
788 pub fn capacity(&self) -> usize {
792 /// Ensures that this `String`'s capacity is at least `additional` bytes
793 /// larger than its length.
795 /// The capacity may be increased by more than `additional` bytes if it
796 /// chooses, to prevent frequent reallocations.
798 /// If you do not want this "at least" behavior, see the [`reserve_exact()`]
801 /// [`reserve_exact()`]: #method.reserve_exact
805 /// Panics if the new capacity overflows `usize`.
812 /// let mut s = String::new();
816 /// assert!(s.capacity() >= 10);
819 /// This may not actually increase the capacity:
822 /// let mut s = String::with_capacity(10);
826 /// // s now has a length of 2 and a capacity of 10
827 /// assert_eq!(2, s.len());
828 /// assert_eq!(10, s.capacity());
830 /// // Since we already have an extra 8 capacity, calling this...
833 /// // ... doesn't actually increase.
834 /// assert_eq!(10, s.capacity());
837 #[stable(feature = "rust1", since = "1.0.0")]
838 pub fn reserve(&mut self, additional: usize) {
839 self.vec.reserve(additional)
842 /// Ensures that this `String`'s capacity is `additional` bytes
843 /// larger than its length.
845 /// Consider using the [`reserve()`] method unless you absolutely know
846 /// better than the allocator.
848 /// [`reserve()`]: #method.reserve
852 /// Panics if the new capacity overflows `usize`.
859 /// let mut s = String::new();
861 /// s.reserve_exact(10);
863 /// assert!(s.capacity() >= 10);
866 /// This may not actually increase the capacity:
869 /// let mut s = String::with_capacity(10);
873 /// // s now has a length of 2 and a capacity of 10
874 /// assert_eq!(2, s.len());
875 /// assert_eq!(10, s.capacity());
877 /// // Since we already have an extra 8 capacity, calling this...
878 /// s.reserve_exact(8);
880 /// // ... doesn't actually increase.
881 /// assert_eq!(10, s.capacity());
884 #[stable(feature = "rust1", since = "1.0.0")]
885 pub fn reserve_exact(&mut self, additional: usize) {
886 self.vec.reserve_exact(additional)
889 /// Shrinks the capacity of this `String` to match its length.
896 /// let mut s = String::from("foo");
899 /// assert!(s.capacity() >= 100);
901 /// s.shrink_to_fit();
902 /// assert_eq!(3, s.capacity());
905 #[stable(feature = "rust1", since = "1.0.0")]
906 pub fn shrink_to_fit(&mut self) {
907 self.vec.shrink_to_fit()
910 /// Appends the given `char` to the end of this `String`.
917 /// let mut s = String::from("abc");
923 /// assert_eq!("abc123", s);
926 #[stable(feature = "rust1", since = "1.0.0")]
927 pub fn push(&mut self, ch: char) {
928 match ch.len_utf8() {
929 1 => self.vec.push(ch as u8),
931 let cur_len = self.len();
932 // This may use up to 4 bytes.
933 self.vec.reserve(ch_len);
936 // Attempt to not use an intermediate buffer by just pushing bytes
937 // directly onto this string.
938 let slice = slice::from_raw_parts_mut(self.vec
940 .offset(cur_len as isize),
942 let used = ch.encode_utf8(slice).unwrap_or(0);
943 self.vec.set_len(cur_len + used);
949 /// Returns a byte slice of this `String`'s contents.
956 /// let s = String::from("hello");
958 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
961 #[stable(feature = "rust1", since = "1.0.0")]
962 pub fn as_bytes(&self) -> &[u8] {
966 /// Shortens this `String` to the specified length.
970 /// Panics if `new_len` > current length, or if `new_len` does not lie on a
971 /// [`char`] boundary.
973 /// [`char`]: ../primitive.char.html
980 /// let mut s = String::from("hello");
984 /// assert_eq!("he", s);
987 #[stable(feature = "rust1", since = "1.0.0")]
988 pub fn truncate(&mut self, new_len: usize) {
989 assert!(self.is_char_boundary(new_len));
990 self.vec.truncate(new_len)
993 /// Removes the last character from the string buffer and returns it.
995 /// Returns `None` if this `String` is empty.
1002 /// let mut s = String::from("foo");
1004 /// assert_eq!(s.pop(), Some('o'));
1005 /// assert_eq!(s.pop(), Some('o'));
1006 /// assert_eq!(s.pop(), Some('f'));
1008 /// assert_eq!(s.pop(), None);
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 pub fn pop(&mut self) -> Option<char> {
1013 let len = self.len();
1018 let ch = self.char_at_reverse(len);
1020 self.vec.set_len(len - ch.len_utf8());
1025 /// Removes a `char` from this `String` at a byte position and returns it.
1027 /// This is an `O(n)` operation, as it requires copying every element in the
1032 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1033 /// lie on a [`char`] boundary.
1035 /// [`char`]: ../primitive.char.html
1042 /// let mut s = String::from("foo");
1044 /// assert_eq!(s.remove(0), 'f');
1045 /// assert_eq!(s.remove(1), 'o');
1046 /// assert_eq!(s.remove(0), 'o');
1049 #[stable(feature = "rust1", since = "1.0.0")]
1050 pub fn remove(&mut self, idx: usize) -> char {
1051 let len = self.len();
1052 assert!(idx <= len);
1054 let ch = self.char_at(idx);
1055 let next = idx + ch.len_utf8();
1057 ptr::copy(self.vec.as_ptr().offset(next as isize),
1058 self.vec.as_mut_ptr().offset(idx as isize),
1060 self.vec.set_len(len - (next - idx));
1065 /// Inserts a character into this `String` at a byte position.
1067 /// This is an `O(n)` operation as it requires copying every element in the
1072 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1073 /// lie on a [`char`] boundary.
1075 /// [`char`]: ../primitive.char.html
1082 /// let mut s = String::with_capacity(3);
1084 /// s.insert(0, 'f');
1085 /// s.insert(1, 'o');
1086 /// s.insert(2, 'o');
1088 /// assert_eq!("foo", s);
1091 #[stable(feature = "rust1", since = "1.0.0")]
1092 pub fn insert(&mut self, idx: usize, ch: char) {
1093 let len = self.len();
1094 assert!(idx <= len);
1095 assert!(self.is_char_boundary(idx));
1096 self.vec.reserve(4);
1097 let mut bits = [0; 4];
1098 let amt = ch.encode_utf8(&mut bits).unwrap();
1101 ptr::copy(self.vec.as_ptr().offset(idx as isize),
1102 self.vec.as_mut_ptr().offset((idx + amt) as isize),
1104 ptr::copy(bits.as_ptr(),
1105 self.vec.as_mut_ptr().offset(idx as isize),
1107 self.vec.set_len(len + amt);
1111 /// Returns a mutable reference to the contents of this `String`.
1115 /// This function is unsafe because it does not check that the bytes passed
1116 /// to it are valid UTF-8. If this constraint is violated, it may cause
1117 /// memory unsafety issues with future users of the `String`, as the rest of
1118 /// the standard library assumes that `String`s are valid UTF-8.
1125 /// let mut s = String::from("hello");
1128 /// let vec = s.as_mut_vec();
1129 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1133 /// assert_eq!(s, "olleh");
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1141 /// Returns the length of this `String`, in bytes.
1148 /// let a = String::from("foo");
1150 /// assert_eq!(a.len(), 3);
1153 #[stable(feature = "rust1", since = "1.0.0")]
1154 pub fn len(&self) -> usize {
1158 /// Returns `true` if this `String` has a length of zero.
1160 /// Returns `false` otherwise.
1167 /// let mut v = String::new();
1168 /// assert!(v.is_empty());
1171 /// assert!(!v.is_empty());
1174 #[stable(feature = "rust1", since = "1.0.0")]
1175 pub fn is_empty(&self) -> bool {
1179 /// Truncates this `String`, removing all contents.
1181 /// While this means the `String` will have a length of zero, it does not
1182 /// touch its capacity.
1189 /// let mut s = String::from("foo");
1193 /// assert!(s.is_empty());
1194 /// assert_eq!(0, s.len());
1195 /// assert_eq!(3, s.capacity());
1198 #[stable(feature = "rust1", since = "1.0.0")]
1199 pub fn clear(&mut self) {
1203 /// Create a draining iterator that removes the specified range in the string
1204 /// and yields the removed chars from start to end. The element range is
1205 /// removed even if the iterator is not consumed until the end.
1209 /// Panics if the starting point or end point do not lie on a [`char`]
1210 /// boundary, or if they're out of bounds.
1212 /// [`char`]: ../primitive.char.html
1219 /// let mut s = String::from("α is alpha, β is beta");
1220 /// let beta_offset = s.find('β').unwrap_or(s.len());
1222 /// // Remove the range up until the β from the string
1223 /// let t: String = s.drain(..beta_offset).collect();
1224 /// assert_eq!(t, "α is alpha, ");
1225 /// assert_eq!(s, "β is beta");
1227 /// // A full range clears the string
1229 /// assert_eq!(s, "");
1231 #[stable(feature = "drain", since = "1.6.0")]
1232 pub fn drain<R>(&mut self, range: R) -> Drain
1233 where R: RangeArgument<usize>
1237 // The String version of Drain does not have the memory safety issues
1238 // of the vector version. The data is just plain bytes.
1239 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1240 // the removal will not happen.
1241 let len = self.len();
1242 let start = *range.start().unwrap_or(&0);
1243 let end = *range.end().unwrap_or(&len);
1245 // Take out two simultaneous borrows. The &mut String won't be accessed
1246 // until iteration is over, in Drop.
1247 let self_ptr = self as *mut _;
1248 // slicing does the appropriate bounds checks
1249 let chars_iter = self[start..end].chars();
1259 /// Converts this `String` into a `Box<str>`.
1261 /// This will drop any excess capacity.
1268 /// let s = String::from("hello");
1270 /// let b = s.into_boxed_str();
1272 #[stable(feature = "box_str", since = "1.4.0")]
1273 pub fn into_boxed_str(self) -> Box<str> {
1274 let slice = self.vec.into_boxed_slice();
1275 unsafe { mem::transmute::<Box<[u8]>, Box<str>>(slice) }
1279 impl FromUtf8Error {
1280 /// Returns the bytes that were attempted to convert to a `String`.
1282 /// This method is carefully constructed to avoid allocation. It will
1283 /// consume the error, moving out the bytes, so that a copy of the bytes
1284 /// does not need to be made.
1291 /// // some invalid bytes, in a vector
1292 /// let bytes = vec![0, 159];
1294 /// let value = String::from_utf8(bytes);
1296 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1298 #[stable(feature = "rust1", since = "1.0.0")]
1299 pub fn into_bytes(self) -> Vec<u8> {
1303 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1305 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1306 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1307 /// an analogue to `FromUtf8Error`. See its documentation for more details
1310 /// [`Utf8Error`]: ../str/struct.Utf8Error.html
1311 /// [`std::str`]: ../str/index.html
1318 /// // some invalid bytes, in a vector
1319 /// let bytes = vec![0, 159];
1321 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1323 /// // the first byte is invalid here
1324 /// assert_eq!(1, error.valid_up_to());
1326 #[stable(feature = "rust1", since = "1.0.0")]
1327 pub fn utf8_error(&self) -> Utf8Error {
1332 #[stable(feature = "rust1", since = "1.0.0")]
1333 impl fmt::Display for FromUtf8Error {
1334 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1335 fmt::Display::fmt(&self.error, f)
1339 #[stable(feature = "rust1", since = "1.0.0")]
1340 impl fmt::Display for FromUtf16Error {
1341 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1342 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1346 #[stable(feature = "rust1", since = "1.0.0")]
1347 impl Clone for String {
1348 fn clone(&self) -> Self {
1349 String { vec: self.vec.clone() }
1352 fn clone_from(&mut self, source: &Self) {
1353 self.vec.clone_from(&source.vec);
1357 #[stable(feature = "rust1", since = "1.0.0")]
1358 impl FromIterator<char> for String {
1359 fn from_iter<I: IntoIterator<Item = char>>(iterable: I) -> String {
1360 let mut buf = String::new();
1361 buf.extend(iterable);
1366 #[stable(feature = "rust1", since = "1.0.0")]
1367 impl<'a> FromIterator<&'a str> for String {
1368 fn from_iter<I: IntoIterator<Item = &'a str>>(iterable: I) -> String {
1369 let mut buf = String::new();
1370 buf.extend(iterable);
1375 #[stable(feature = "extend_string", since = "1.4.0")]
1376 impl FromIterator<String> for String {
1377 fn from_iter<I: IntoIterator<Item = String>>(iterable: I) -> String {
1378 let mut buf = String::new();
1379 buf.extend(iterable);
1384 #[stable(feature = "rust1", since = "1.0.0")]
1385 impl Extend<char> for String {
1386 fn extend<I: IntoIterator<Item = char>>(&mut self, iterable: I) {
1387 let iterator = iterable.into_iter();
1388 let (lower_bound, _) = iterator.size_hint();
1389 self.reserve(lower_bound);
1390 for ch in iterator {
1396 #[stable(feature = "extend_ref", since = "1.2.0")]
1397 impl<'a> Extend<&'a char> for String {
1398 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iterable: I) {
1399 self.extend(iterable.into_iter().cloned());
1403 #[stable(feature = "rust1", since = "1.0.0")]
1404 impl<'a> Extend<&'a str> for String {
1405 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iterable: I) {
1412 #[stable(feature = "extend_string", since = "1.4.0")]
1413 impl Extend<String> for String {
1414 fn extend<I: IntoIterator<Item = String>>(&mut self, iterable: I) {
1421 /// A convenience impl that delegates to the impl for `&str`
1422 #[unstable(feature = "pattern",
1423 reason = "API not fully fleshed out and ready to be stabilized",
1425 impl<'a, 'b> Pattern<'a> for &'b String {
1426 type Searcher = <&'b str as Pattern<'a>>::Searcher;
1428 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1429 self[..].into_searcher(haystack)
1433 fn is_contained_in(self, haystack: &'a str) -> bool {
1434 self[..].is_contained_in(haystack)
1438 fn is_prefix_of(self, haystack: &'a str) -> bool {
1439 self[..].is_prefix_of(haystack)
1443 #[stable(feature = "rust1", since = "1.0.0")]
1444 impl PartialEq for String {
1446 fn eq(&self, other: &String) -> bool {
1447 PartialEq::eq(&self[..], &other[..])
1450 fn ne(&self, other: &String) -> bool {
1451 PartialEq::ne(&self[..], &other[..])
1455 macro_rules! impl_eq {
1456 ($lhs:ty, $rhs: ty) => {
1457 #[stable(feature = "rust1", since = "1.0.0")]
1458 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1460 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1462 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1465 #[stable(feature = "rust1", since = "1.0.0")]
1466 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1468 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1470 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1476 impl_eq! { String, str }
1477 impl_eq! { String, &'a str }
1478 impl_eq! { Cow<'a, str>, str }
1479 impl_eq! { Cow<'a, str>, &'b str }
1480 impl_eq! { Cow<'a, str>, String }
1482 #[stable(feature = "rust1", since = "1.0.0")]
1483 impl Default for String {
1485 fn default() -> String {
1490 #[stable(feature = "rust1", since = "1.0.0")]
1491 impl fmt::Display for String {
1493 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1494 fmt::Display::fmt(&**self, f)
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 impl fmt::Debug for String {
1501 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1502 fmt::Debug::fmt(&**self, f)
1506 #[stable(feature = "rust1", since = "1.0.0")]
1507 impl hash::Hash for String {
1509 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1510 (**self).hash(hasher)
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 impl<'a> Add<&'a str> for String {
1516 type Output = String;
1519 fn add(mut self, other: &str) -> String {
1520 self.push_str(other);
1525 #[stable(feature = "rust1", since = "1.0.0")]
1526 impl ops::Index<ops::Range<usize>> for String {
1530 fn index(&self, index: ops::Range<usize>) -> &str {
1534 #[stable(feature = "rust1", since = "1.0.0")]
1535 impl ops::Index<ops::RangeTo<usize>> for String {
1539 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1543 #[stable(feature = "rust1", since = "1.0.0")]
1544 impl ops::Index<ops::RangeFrom<usize>> for String {
1548 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1552 #[stable(feature = "rust1", since = "1.0.0")]
1553 impl ops::Index<ops::RangeFull> for String {
1557 fn index(&self, _index: ops::RangeFull) -> &str {
1558 unsafe { str::from_utf8_unchecked(&self.vec) }
1562 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1563 impl ops::IndexMut<ops::Range<usize>> for String {
1565 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1566 &mut self[..][index]
1569 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1570 impl ops::IndexMut<ops::RangeTo<usize>> for String {
1572 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1573 &mut self[..][index]
1576 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1577 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
1579 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1580 &mut self[..][index]
1583 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1584 impl ops::IndexMut<ops::RangeFull> for String {
1586 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1587 unsafe { mem::transmute(&mut *self.vec) }
1591 #[stable(feature = "rust1", since = "1.0.0")]
1592 impl ops::Deref for String {
1596 fn deref(&self) -> &str {
1597 unsafe { str::from_utf8_unchecked(&self.vec) }
1601 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1602 impl ops::DerefMut for String {
1604 fn deref_mut(&mut self) -> &mut str {
1605 unsafe { mem::transmute(&mut *self.vec) }
1609 /// An error when parsing a `String`.
1611 /// This `enum` is slightly awkward: it will never actually exist. This error is
1612 /// part of the type signature of the implementation of [`FromStr`] on
1613 /// [`String`]. The return type of [`from_str()`], requires that an error be
1614 /// defined, but, given that a [`String`] can always be made into a new
1615 /// [`String`] without error, this type will never actually be returned. As
1616 /// such, it is only here to satisfy said signature, and is useless otherwise.
1618 /// [`FromStr`]: ../str/trait.FromStr.html
1619 /// [`String`]: struct.String.html
1620 /// [`from_str()`]: ../str/trait.FromStr.html#tymethod.from_str
1621 #[stable(feature = "str_parse_error", since = "1.5.0")]
1623 pub enum ParseError {}
1625 #[stable(feature = "rust1", since = "1.0.0")]
1626 impl FromStr for String {
1627 type Err = ParseError;
1629 fn from_str(s: &str) -> Result<String, ParseError> {
1634 #[stable(feature = "str_parse_error", since = "1.5.0")]
1635 impl Clone for ParseError {
1636 fn clone(&self) -> ParseError {
1641 #[stable(feature = "str_parse_error", since = "1.5.0")]
1642 impl fmt::Debug for ParseError {
1643 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1648 #[stable(feature = "str_parse_error", since = "1.5.0")]
1649 impl PartialEq for ParseError {
1650 fn eq(&self, _: &ParseError) -> bool {
1655 #[stable(feature = "str_parse_error", since = "1.5.0")]
1656 impl Eq for ParseError {}
1658 /// A trait for converting a value to a `String`.
1660 /// This trait is automatically implemented for any type which implements the
1661 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
1662 /// [`Display`] should be implemented instead, and you get the `ToString`
1663 /// implementation for free.
1665 /// [`Display`]: ../fmt/trait.Display.html
1666 #[stable(feature = "rust1", since = "1.0.0")]
1667 pub trait ToString {
1668 /// Converts the given value to a `String`.
1676 /// let five = String::from("5");
1678 /// assert_eq!(five, i.to_string());
1680 #[stable(feature = "rust1", since = "1.0.0")]
1681 fn to_string(&self) -> String;
1684 #[stable(feature = "rust1", since = "1.0.0")]
1685 impl<T: fmt::Display + ?Sized> ToString for T {
1687 fn to_string(&self) -> String {
1688 use core::fmt::Write;
1689 let mut buf = String::new();
1690 let _ = buf.write_fmt(format_args!("{}", self));
1691 buf.shrink_to_fit();
1696 #[stable(feature = "rust1", since = "1.0.0")]
1697 impl AsRef<str> for String {
1699 fn as_ref(&self) -> &str {
1704 #[stable(feature = "rust1", since = "1.0.0")]
1705 impl AsRef<[u8]> for String {
1707 fn as_ref(&self) -> &[u8] {
1712 #[stable(feature = "rust1", since = "1.0.0")]
1713 impl<'a> From<&'a str> for String {
1716 fn from(s: &'a str) -> String {
1717 String { vec: <[_]>::to_vec(s.as_bytes()) }
1720 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1721 // required for this method definition, is not available. Since we don't
1722 // require this method for testing purposes, I'll just stub it
1723 // NB see the slice::hack module in slice.rs for more information
1726 fn from(_: &str) -> String {
1727 panic!("not available with cfg(test)");
1731 #[stable(feature = "rust1", since = "1.0.0")]
1732 impl<'a> From<&'a str> for Cow<'a, str> {
1734 fn from(s: &'a str) -> Cow<'a, str> {
1739 #[stable(feature = "rust1", since = "1.0.0")]
1740 impl<'a> From<String> for Cow<'a, str> {
1742 fn from(s: String) -> Cow<'a, str> {
1747 #[stable(feature = "rust1", since = "1.0.0")]
1748 impl Into<Vec<u8>> for String {
1749 fn into(self) -> Vec<u8> {
1754 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`",
1756 impl IntoCow<'static, str> for String {
1758 fn into_cow(self) -> Cow<'static, str> {
1763 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`",
1765 impl<'a> IntoCow<'a, str> for &'a str {
1767 fn into_cow(self) -> Cow<'a, str> {
1772 #[stable(feature = "rust1", since = "1.0.0")]
1773 impl fmt::Write for String {
1775 fn write_str(&mut self, s: &str) -> fmt::Result {
1781 fn write_char(&mut self, c: char) -> fmt::Result {
1787 /// A draining iterator for `String`.
1788 #[stable(feature = "drain", since = "1.6.0")]
1789 pub struct Drain<'a> {
1790 /// Will be used as &'a mut String in the destructor
1791 string: *mut String,
1792 /// Start of part to remove
1794 /// End of part to remove
1796 /// Current remaining range to remove
1800 #[stable(feature = "drain", since = "1.6.0")]
1801 unsafe impl<'a> Sync for Drain<'a> {}
1802 #[stable(feature = "drain", since = "1.6.0")]
1803 unsafe impl<'a> Send for Drain<'a> {}
1805 #[stable(feature = "drain", since = "1.6.0")]
1806 impl<'a> Drop for Drain<'a> {
1807 fn drop(&mut self) {
1809 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
1810 // panic code being inserted again.
1811 let self_vec = (*self.string).as_mut_vec();
1812 if self.start <= self.end && self.end <= self_vec.len() {
1813 self_vec.drain(self.start..self.end);
1819 #[stable(feature = "drain", since = "1.6.0")]
1820 impl<'a> Iterator for Drain<'a> {
1824 fn next(&mut self) -> Option<char> {
1828 fn size_hint(&self) -> (usize, Option<usize>) {
1829 self.iter.size_hint()
1833 #[stable(feature = "drain", since = "1.6.0")]
1834 impl<'a> DoubleEndedIterator for Drain<'a> {
1836 fn next_back(&mut self) -> Option<char> {
1837 self.iter.next_back()