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 //! An owned, growable string that enforces that its contents are valid UTF-8.
13 #![stable(feature = "rust1", since = "1.0.0")]
17 use core::iter::FromIterator;
19 use core::ops::{self, Deref, Add, Index};
22 use core::str::pattern::Pattern;
23 use rustc_unicode::char::{decode_utf16, REPLACEMENT_CHARACTER};
24 use rustc_unicode::str as unicode_str;
26 use borrow::{Cow, IntoCow};
27 use range::RangeArgument;
28 use str::{self, FromStr, Utf8Error, Chars};
32 /// A growable string stored as a UTF-8 encoded buffer.
33 #[derive(PartialOrd, Eq, Ord)]
34 #[stable(feature = "rust1", since = "1.0.0")]
39 /// A possible error value from the `String::from_utf8` function.
40 #[stable(feature = "rust1", since = "1.0.0")]
42 pub struct FromUtf8Error {
47 /// A possible error value from the `String::from_utf16` function.
48 #[stable(feature = "rust1", since = "1.0.0")]
50 pub struct FromUtf16Error(());
53 /// Creates a new string buffer initialized with the empty string.
58 /// # #![allow(unused_mut)]
59 /// let mut s = String::new();
62 #[stable(feature = "rust1", since = "1.0.0")]
63 pub fn new() -> String {
64 String { vec: Vec::new() }
67 /// Creates a new string buffer with the given capacity.
68 /// The string will be able to hold exactly `capacity` bytes without
69 /// reallocating. If `capacity` is 0, the string will not allocate.
74 /// let mut s = String::with_capacity(10);
76 /// // The String contains no chars, even though it has capacity for more
77 /// assert_eq!(s.len(), 0);
79 /// // These are all done without reallocating...
80 /// let cap = s.capacity();
85 /// assert_eq!(s.capacity(), cap);
87 /// // ...but this may make the vector reallocate
91 #[stable(feature = "rust1", since = "1.0.0")]
92 pub fn with_capacity(capacity: usize) -> String {
93 String { vec: Vec::with_capacity(capacity) }
96 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
97 // required for this method definition, is not available. Since we don't
98 // require this method for testing purposes, I'll just stub it
99 // NB see the slice::hack module in slice.rs for more information
102 pub fn from_str(_: &str) -> String {
103 panic!("not available with cfg(test)");
106 /// Converts a vector of bytes to a `String`.
108 /// A string slice (`&str`) is made of bytes (`u8`), and a vector of bytes
109 /// (`Vec<u8>`) is made of bytes, so this function converts between the
110 /// two. Not all byte slices are valid `String`s, however: `String`
111 /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
112 /// the bytes are valid UTF-8, and then does the conversion.
114 /// If you are sure that the byte slice is valid UTF-8, and you don't want
115 /// to incur the overhead of the validity check, there is an unsafe version
116 /// of this function, [`from_utf8_unchecked()`][fromutf8], which has the
117 /// same behavior but skips the check.
119 /// [fromutf8]: struct.String.html#method.from_utf8_unchecked
121 /// This method will take care to not copy the vector, for efficiency's
124 /// If you need a `&str` instead of a `String`, consider
125 /// [`str::from_utf8()`][str].
127 /// [str]: ../str/fn.from_utf8.html
131 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
132 /// provided bytes are not UTF-8. The vector you moved in is also included.
139 /// // some bytes, in a vector
140 /// let sparkle_heart = vec![240, 159, 146, 150];
142 /// // We know these bytes are valid, so just use `unwrap()`.
143 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
145 /// assert_eq!("💖", sparkle_heart);
151 /// // some invalid bytes, in a vector
152 /// let sparkle_heart = vec![0, 159, 146, 150];
154 /// assert!(String::from_utf8(sparkle_heart).is_err());
157 /// See the docs for [`FromUtf8Error`][error] for more details on what you
158 /// can do with this error.
160 /// [error]: struct.FromUtf8Error.html
162 #[stable(feature = "rust1", since = "1.0.0")]
163 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
164 match str::from_utf8(&vec) {
165 Ok(..) => Ok(String { vec: vec }),
175 /// Converts a slice of bytes to a `String`, including invalid characters.
177 /// A string slice (`&str`) is made of bytes (`u8`), and a slice of bytes
178 /// (`&[u8]`) is made of bytes, so this function converts between the two.
179 /// Not all byte slices are valid string slices, however: `&str` requires
180 /// that it is valid UTF-8. During this conversion, `from_utf8_lossy()`
181 /// will replace any invalid UTF-8 sequences with
182 /// `U+FFFD REPLACEMENT CHARACTER`, which looks like this: �
184 /// If you are sure that the byte slice is valid UTF-8, and you don't want
185 /// to incur the overhead of the conversion, there is an unsafe version
186 /// of this function, [`from_utf8_unchecked()`][fromutf8], which has the
187 /// same behavior but skips the checks.
189 /// [fromutf8]: struct.String.html#method.from_utf8_unchecked
191 /// If you need a `&str` instead of a `String`, consider
192 /// [`str::from_utf8()`][str].
194 /// [str]: ../str/fn.from_utf8.html
201 /// // some bytes, in a vector
202 /// let sparkle_heart = vec![240, 159, 146, 150];
204 /// // We know these bytes are valid, so just use `unwrap()`.
205 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
207 /// assert_eq!("💖", sparkle_heart);
213 /// // some invalid bytes
214 /// let input = b"Hello \xF0\x90\x80World";
215 /// let output = String::from_utf8_lossy(input);
217 /// assert_eq!("Hello �World", output);
219 #[stable(feature = "rust1", since = "1.0.0")]
220 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
222 match str::from_utf8(v) {
223 Ok(s) => return Cow::Borrowed(s),
224 Err(e) => i = e.valid_up_to(),
227 const TAG_CONT_U8: u8 = 128;
228 const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
230 fn unsafe_get(xs: &[u8], i: usize) -> u8 {
231 unsafe { *xs.get_unchecked(i) }
233 fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 {
241 let mut res = String::with_capacity(total);
244 unsafe { res.as_mut_vec().push_all(&v[..i]) };
247 // subseqidx is the index of the first byte of the subsequence we're
248 // looking at. It's used to copy a bunch of contiguous good codepoints
249 // at once instead of copying them one by one.
250 let mut subseqidx = i;
254 let byte = unsafe_get(v, i);
257 macro_rules! error { () => ({
260 res.as_mut_vec().push_all(&v[subseqidx..i_]);
263 res.as_mut_vec().push_all(REPLACEMENT);
268 // subseqidx handles this
270 let w = unicode_str::utf8_char_width(byte);
274 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
281 match (byte, safe_get(v, i, total)) {
282 (0xE0, 0xA0...0xBF) => (),
283 (0xE1...0xEC, 0x80...0xBF) => (),
284 (0xED, 0x80...0x9F) => (),
285 (0xEE...0xEF, 0x80...0xBF) => (),
292 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
299 match (byte, safe_get(v, i, total)) {
300 (0xF0, 0x90...0xBF) => (),
301 (0xF1...0xF3, 0x80...0xBF) => (),
302 (0xF4, 0x80...0x8F) => (),
309 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
314 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
327 if subseqidx < total {
328 unsafe { res.as_mut_vec().push_all(&v[subseqidx..total]) };
333 /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
334 /// if `v` contains any invalid data.
340 /// let mut v = &mut [0xD834, 0xDD1E, 0x006d, 0x0075,
341 /// 0x0073, 0x0069, 0x0063];
342 /// assert_eq!(String::from_utf16(v).unwrap(),
343 /// "𝄞music".to_string());
345 /// // 𝄞mu<invalid>ic
347 /// assert!(String::from_utf16(v).is_err());
349 #[stable(feature = "rust1", since = "1.0.0")]
350 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
351 decode_utf16(v.iter().cloned()).collect::<Result<_, _>>().map_err(|_| FromUtf16Error(()))
354 /// Decode a UTF-16 encoded vector `v` into a string, replacing
355 /// invalid data with the replacement character (U+FFFD).
360 /// // 𝄞mus<invalid>ic<invalid>
361 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
362 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
365 /// assert_eq!(String::from_utf16_lossy(v),
366 /// "𝄞mus\u{FFFD}ic\u{FFFD}".to_string());
369 #[stable(feature = "rust1", since = "1.0.0")]
370 pub fn from_utf16_lossy(v: &[u16]) -> String {
371 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
374 /// Creates a new `String` from a length, capacity, and pointer.
378 /// This is _very_ unsafe because:
380 /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`. Therefore, this
381 /// function inherits all of its unsafety, see [its
382 /// documentation](../vec/struct.Vec.html#method.from_raw_parts)
383 /// for the invariants it expects, they also apply to this function.
384 /// * We assume that the `Vec` contains valid UTF-8.
386 #[stable(feature = "rust1", since = "1.0.0")]
387 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
388 String { vec: Vec::from_raw_parts(buf, length, capacity) }
391 /// Converts a vector of bytes to a `String` without checking that the
392 /// string contains valid UTF-8.
394 /// See the safe version, [`from_utf8()`][fromutf8], for more.
396 /// [fromutf8]: struct.String.html#method.from_utf8
400 /// This function is unsafe because it does not check that the bytes passed to
401 /// it are valid UTF-8. If this constraint is violated, undefined behavior
402 /// results, as the rest of Rust assumes that `String`s are valid UTF-8.
409 /// // some bytes, in a vector
410 /// let sparkle_heart = vec![240, 159, 146, 150];
412 /// let sparkle_heart = unsafe {
413 /// String::from_utf8_unchecked(sparkle_heart)
416 /// assert_eq!("💖", sparkle_heart);
419 #[stable(feature = "rust1", since = "1.0.0")]
420 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
421 String { vec: bytes }
424 /// Returns the underlying byte buffer, encoded as UTF-8.
429 /// let s = String::from("hello");
430 /// let bytes = s.into_bytes();
431 /// assert_eq!(bytes, [104, 101, 108, 108, 111]);
434 #[stable(feature = "rust1", since = "1.0.0")]
435 pub fn into_bytes(self) -> Vec<u8> {
439 /// Extracts a string slice containing the entire string.
441 #[unstable(feature = "convert",
442 reason = "waiting on RFC revision",
444 pub fn as_str(&self) -> &str {
448 /// Pushes the given string onto this string buffer.
453 /// let mut s = String::from("foo");
454 /// s.push_str("bar");
455 /// assert_eq!(s, "foobar");
458 #[stable(feature = "rust1", since = "1.0.0")]
459 pub fn push_str(&mut self, string: &str) {
460 self.vec.push_all(string.as_bytes())
463 /// Returns the number of bytes that this string buffer can hold without
469 /// let s = String::with_capacity(10);
470 /// assert!(s.capacity() >= 10);
473 #[stable(feature = "rust1", since = "1.0.0")]
474 pub fn capacity(&self) -> usize {
478 /// Reserves capacity for at least `additional` more bytes to be inserted
479 /// in the given `String`. The collection may reserve more space to avoid
480 /// frequent reallocations.
484 /// Panics if the new capacity overflows `usize`.
489 /// let mut s = String::new();
491 /// assert!(s.capacity() >= 10);
494 #[stable(feature = "rust1", since = "1.0.0")]
495 pub fn reserve(&mut self, additional: usize) {
496 self.vec.reserve(additional)
499 /// Reserves the minimum capacity for exactly `additional` more bytes to be
500 /// inserted in the given `String`. Does nothing if the capacity is already
503 /// Note that the allocator may give the collection more space than it
504 /// requests. Therefore capacity can not be relied upon to be precisely
505 /// minimal. Prefer `reserve` if future insertions are expected.
509 /// Panics if the new capacity overflows `usize`.
514 /// let mut s = String::new();
515 /// s.reserve_exact(10);
516 /// assert!(s.capacity() >= 10);
519 #[stable(feature = "rust1", since = "1.0.0")]
520 pub fn reserve_exact(&mut self, additional: usize) {
521 self.vec.reserve_exact(additional)
524 /// Shrinks the capacity of this string buffer to match its length.
529 /// let mut s = String::from("foo");
531 /// assert!(s.capacity() >= 100);
532 /// s.shrink_to_fit();
533 /// assert_eq!(s.capacity(), 3);
536 #[stable(feature = "rust1", since = "1.0.0")]
537 pub fn shrink_to_fit(&mut self) {
538 self.vec.shrink_to_fit()
541 /// Adds the given character to the end of the string.
546 /// let mut s = String::from("abc");
550 /// assert_eq!(s, "abc123");
553 #[stable(feature = "rust1", since = "1.0.0")]
554 pub fn push(&mut self, ch: char) {
555 match ch.len_utf8() {
556 1 => self.vec.push(ch as u8),
558 let cur_len = self.len();
559 // This may use up to 4 bytes.
560 self.vec.reserve(ch_len);
563 // Attempt to not use an intermediate buffer by just pushing bytes
564 // directly onto this string.
565 let slice = slice::from_raw_parts_mut(self.vec
567 .offset(cur_len as isize),
569 let used = ch.encode_utf8(slice).unwrap_or(0);
570 self.vec.set_len(cur_len + used);
576 /// Works with the underlying buffer as a byte slice.
581 /// let s = String::from("hello");
582 /// assert_eq!(s.as_bytes(), [104, 101, 108, 108, 111]);
585 #[stable(feature = "rust1", since = "1.0.0")]
586 pub fn as_bytes(&self) -> &[u8] {
590 /// Shortens a string to the specified length.
594 /// Panics if `new_len` > current length,
595 /// or if `new_len` is not a character boundary.
600 /// let mut s = String::from("hello");
602 /// assert_eq!(s, "he");
605 #[stable(feature = "rust1", since = "1.0.0")]
606 pub fn truncate(&mut self, new_len: usize) {
607 assert!(self.is_char_boundary(new_len));
608 self.vec.truncate(new_len)
611 /// Removes the last character from the string buffer and returns it.
612 /// Returns `None` if this string buffer is empty.
617 /// let mut s = String::from("foo");
618 /// assert_eq!(s.pop(), Some('o'));
619 /// assert_eq!(s.pop(), Some('o'));
620 /// assert_eq!(s.pop(), Some('f'));
621 /// assert_eq!(s.pop(), None);
624 #[stable(feature = "rust1", since = "1.0.0")]
625 pub fn pop(&mut self) -> Option<char> {
626 let len = self.len();
631 let ch = self.char_at_reverse(len);
633 self.vec.set_len(len - ch.len_utf8());
638 /// Removes the character from the string buffer at byte position `idx` and
643 /// This is an O(n) operation as it requires copying every element in the
648 /// If `idx` does not lie on a character boundary, or if it is out of
649 /// bounds, then this function will panic.
654 /// let mut s = String::from("foo");
655 /// assert_eq!(s.remove(0), 'f');
656 /// assert_eq!(s.remove(1), 'o');
657 /// assert_eq!(s.remove(0), 'o');
660 #[stable(feature = "rust1", since = "1.0.0")]
661 pub fn remove(&mut self, idx: usize) -> char {
662 let len = self.len();
665 let ch = self.char_at(idx);
666 let next = idx + ch.len_utf8();
668 ptr::copy(self.vec.as_ptr().offset(next as isize),
669 self.vec.as_mut_ptr().offset(idx as isize),
671 self.vec.set_len(len - (next - idx));
676 /// Inserts a character into the string buffer at byte position `idx`.
680 /// This is an O(n) operation as it requires copying every element in the
685 /// If `idx` does not lie on a character boundary or is out of bounds, then
686 /// this function will panic.
688 #[stable(feature = "rust1", since = "1.0.0")]
689 pub fn insert(&mut self, idx: usize, ch: char) {
690 let len = self.len();
692 assert!(self.is_char_boundary(idx));
694 let mut bits = [0; 4];
695 let amt = ch.encode_utf8(&mut bits).unwrap();
698 ptr::copy(self.vec.as_ptr().offset(idx as isize),
699 self.vec.as_mut_ptr().offset((idx + amt) as isize),
701 ptr::copy(bits.as_ptr(),
702 self.vec.as_mut_ptr().offset(idx as isize),
704 self.vec.set_len(len + amt);
708 /// Views the string buffer as a mutable sequence of bytes.
710 /// This is unsafe because it does not check
711 /// to ensure that the resulting string will be valid UTF-8.
716 /// let mut s = String::from("hello");
718 /// let vec = s.as_mut_vec();
719 /// assert!(vec == &[104, 101, 108, 108, 111]);
722 /// assert_eq!(s, "olleh");
725 #[stable(feature = "rust1", since = "1.0.0")]
726 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
730 /// Returns the number of bytes in this string.
735 /// let a = "foo".to_string();
736 /// assert_eq!(a.len(), 3);
739 #[stable(feature = "rust1", since = "1.0.0")]
740 pub fn len(&self) -> usize {
744 /// Returns true if the string contains no bytes
749 /// let mut v = String::new();
750 /// assert!(v.is_empty());
752 /// assert!(!v.is_empty());
755 #[stable(feature = "rust1", since = "1.0.0")]
756 pub fn is_empty(&self) -> bool {
760 /// Truncates the string, returning it to 0 length.
765 /// let mut s = "foo".to_string();
767 /// assert!(s.is_empty());
770 #[stable(feature = "rust1", since = "1.0.0")]
771 pub fn clear(&mut self) {
775 /// Create a draining iterator that removes the specified range in the string
776 /// and yields the removed chars from start to end. The element range is
777 /// removed even if the iterator is not consumed until the end.
781 /// Panics if the starting point or end point are not on character boundaries,
782 /// or if they are out of bounds.
787 /// #![feature(drain)]
789 /// let mut s = String::from("α is alpha, β is beta");
790 /// let beta_offset = s.find('β').unwrap_or(s.len());
792 /// // Remove the range up until the β from the string
793 /// let t: String = s.drain(..beta_offset).collect();
794 /// assert_eq!(t, "α is alpha, ");
795 /// assert_eq!(s, "β is beta");
797 /// // A full range clears the string
799 /// assert_eq!(s, "");
801 #[unstable(feature = "drain",
802 reason = "recently added, matches RFC",
804 pub fn drain<R>(&mut self, range: R) -> Drain
805 where R: RangeArgument<usize>
809 // The String version of Drain does not have the memory safety issues
810 // of the vector version. The data is just plain bytes.
811 // Because the range removal happens in Drop, if the Drain iterator is leaked,
812 // the removal will not happen.
813 let len = self.len();
814 let start = *range.start().unwrap_or(&0);
815 let end = *range.end().unwrap_or(&len);
817 // Take out two simultaneous borrows. The &mut String won't be accessed
818 // until iteration is over, in Drop.
819 let self_ptr = self as *mut _;
820 // slicing does the appropriate bounds checks
821 let chars_iter = self[start..end].chars();
831 /// Converts the string into `Box<str>`.
833 /// Note that this will drop any excess capacity.
834 #[stable(feature = "box_str", since = "1.4.0")]
835 pub fn into_boxed_str(self) -> Box<str> {
836 let slice = self.vec.into_boxed_slice();
837 unsafe { mem::transmute::<Box<[u8]>, Box<str>>(slice) }
840 /// Converts the string into `Box<str>`.
842 /// Note that this will drop any excess capacity.
843 #[unstable(feature = "box_str2",
844 reason = "recently added, matches RFC",
846 #[deprecated(since = "1.4.0", reason = "renamed to `into_boxed_str`")]
847 pub fn into_boxed_slice(self) -> Box<str> {
848 self.into_boxed_str()
853 /// Consumes this error, returning the bytes that were attempted to make a
855 #[stable(feature = "rust1", since = "1.0.0")]
856 pub fn into_bytes(self) -> Vec<u8> {
860 /// Access the underlying UTF8-error that was the cause of this error.
861 #[stable(feature = "rust1", since = "1.0.0")]
862 pub fn utf8_error(&self) -> Utf8Error {
867 #[stable(feature = "rust1", since = "1.0.0")]
868 impl fmt::Display for FromUtf8Error {
869 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
870 fmt::Display::fmt(&self.error, f)
874 #[stable(feature = "rust1", since = "1.0.0")]
875 impl fmt::Display for FromUtf16Error {
876 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
877 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
881 #[stable(feature = "rust1", since = "1.0.0")]
882 impl Clone for String {
883 fn clone(&self) -> Self {
884 String { vec: self.vec.clone() }
887 fn clone_from(&mut self, source: &Self) {
888 self.vec.clone_from(&source.vec);
892 #[stable(feature = "rust1", since = "1.0.0")]
893 impl FromIterator<char> for String {
894 fn from_iter<I: IntoIterator<Item = char>>(iterable: I) -> String {
895 let mut buf = String::new();
896 buf.extend(iterable);
901 #[stable(feature = "rust1", since = "1.0.0")]
902 impl<'a> FromIterator<&'a str> for String {
903 fn from_iter<I: IntoIterator<Item = &'a str>>(iterable: I) -> String {
904 let mut buf = String::new();
905 buf.extend(iterable);
910 #[stable(feature = "extend_string", since = "1.4.0")]
911 impl FromIterator<String> for String {
912 fn from_iter<I: IntoIterator<Item = String>>(iterable: I) -> String {
913 let mut buf = String::new();
914 buf.extend(iterable);
919 #[stable(feature = "rust1", since = "1.0.0")]
920 impl Extend<char> for String {
921 fn extend<I: IntoIterator<Item = char>>(&mut self, iterable: I) {
922 let iterator = iterable.into_iter();
923 let (lower_bound, _) = iterator.size_hint();
924 self.reserve(lower_bound);
931 #[stable(feature = "extend_ref", since = "1.2.0")]
932 impl<'a> Extend<&'a char> for String {
933 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iterable: I) {
934 self.extend(iterable.into_iter().cloned());
938 #[stable(feature = "rust1", since = "1.0.0")]
939 impl<'a> Extend<&'a str> for String {
940 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iterable: I) {
947 #[stable(feature = "extend_string", since = "1.4.0")]
948 impl Extend<String> for String {
949 fn extend<I: IntoIterator<Item = String>>(&mut self, iterable: I) {
956 /// A convenience impl that delegates to the impl for `&str`
957 #[unstable(feature = "pattern",
958 reason = "API not fully fleshed out and ready to be stabilized",
960 impl<'a, 'b> Pattern<'a> for &'b String {
961 type Searcher = <&'b str as Pattern<'a>>::Searcher;
963 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
964 self[..].into_searcher(haystack)
968 fn is_contained_in(self, haystack: &'a str) -> bool {
969 self[..].is_contained_in(haystack)
973 fn is_prefix_of(self, haystack: &'a str) -> bool {
974 self[..].is_prefix_of(haystack)
978 #[stable(feature = "rust1", since = "1.0.0")]
979 impl PartialEq for String {
981 fn eq(&self, other: &String) -> bool {
982 PartialEq::eq(&self[..], &other[..])
985 fn ne(&self, other: &String) -> bool {
986 PartialEq::ne(&self[..], &other[..])
990 macro_rules! impl_eq {
991 ($lhs:ty, $rhs: ty) => {
992 #[stable(feature = "rust1", since = "1.0.0")]
993 impl<'a, 'b> PartialEq<$rhs> for $lhs {
995 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
997 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1000 #[stable(feature = "rust1", since = "1.0.0")]
1001 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1003 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1005 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1011 impl_eq! { String, str }
1012 impl_eq! { String, &'a str }
1013 impl_eq! { Cow<'a, str>, str }
1014 impl_eq! { Cow<'a, str>, &'b str }
1015 impl_eq! { Cow<'a, str>, String }
1017 #[stable(feature = "rust1", since = "1.0.0")]
1018 impl Default for String {
1020 fn default() -> String {
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 impl fmt::Display for String {
1028 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1029 fmt::Display::fmt(&**self, f)
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 impl fmt::Debug for String {
1036 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1037 fmt::Debug::fmt(&**self, f)
1041 #[stable(feature = "rust1", since = "1.0.0")]
1042 impl hash::Hash for String {
1044 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1045 (**self).hash(hasher)
1049 #[stable(feature = "rust1", since = "1.0.0")]
1050 impl<'a> Add<&'a str> for String {
1051 type Output = String;
1054 fn add(mut self, other: &str) -> String {
1055 self.push_str(other);
1060 #[stable(feature = "rust1", since = "1.0.0")]
1061 impl ops::Index<ops::Range<usize>> for String {
1065 fn index(&self, index: ops::Range<usize>) -> &str {
1069 #[stable(feature = "rust1", since = "1.0.0")]
1070 impl ops::Index<ops::RangeTo<usize>> for String {
1074 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1078 #[stable(feature = "rust1", since = "1.0.0")]
1079 impl ops::Index<ops::RangeFrom<usize>> for String {
1083 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1087 #[stable(feature = "rust1", since = "1.0.0")]
1088 impl ops::Index<ops::RangeFull> for String {
1092 fn index(&self, _index: ops::RangeFull) -> &str {
1093 unsafe { str::from_utf8_unchecked(&self.vec) }
1097 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1098 impl ops::IndexMut<ops::Range<usize>> for String {
1100 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1101 &mut self[..][index]
1104 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1105 impl ops::IndexMut<ops::RangeTo<usize>> for String {
1107 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1108 &mut self[..][index]
1111 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1112 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
1114 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1115 &mut self[..][index]
1118 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1119 impl ops::IndexMut<ops::RangeFull> for String {
1121 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1122 unsafe { mem::transmute(&mut *self.vec) }
1126 #[stable(feature = "rust1", since = "1.0.0")]
1127 impl ops::Deref for String {
1131 fn deref(&self) -> &str {
1132 unsafe { str::from_utf8_unchecked(&self.vec) }
1136 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1137 impl ops::DerefMut for String {
1139 fn deref_mut(&mut self) -> &mut str {
1140 unsafe { mem::transmute(&mut *self.vec) }
1144 /// Error returned from `String::from`
1145 #[stable(feature = "str_parse_error", since = "1.5.0")]
1147 pub enum ParseError {}
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 impl FromStr for String {
1151 type Err = ParseError;
1153 fn from_str(s: &str) -> Result<String, ParseError> {
1158 #[stable(feature = "str_parse_error", since = "1.5.0")]
1159 impl Clone for ParseError {
1160 fn clone(&self) -> ParseError {
1165 #[stable(feature = "str_parse_error", since = "1.5.0")]
1166 impl fmt::Debug for ParseError {
1167 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1172 #[stable(feature = "str_parse_error", since = "1.5.0")]
1173 impl PartialEq for ParseError {
1174 fn eq(&self, _: &ParseError) -> bool {
1179 #[stable(feature = "str_parse_error", since = "1.5.0")]
1180 impl Eq for ParseError {}
1182 /// A generic trait for converting a value to a string
1183 #[stable(feature = "rust1", since = "1.0.0")]
1184 pub trait ToString {
1185 /// Converts the value of `self` to an owned string
1186 #[stable(feature = "rust1", since = "1.0.0")]
1187 fn to_string(&self) -> String;
1190 #[stable(feature = "rust1", since = "1.0.0")]
1191 impl<T: fmt::Display + ?Sized> ToString for T {
1193 fn to_string(&self) -> String {
1194 use core::fmt::Write;
1195 let mut buf = String::new();
1196 let _ = buf.write_fmt(format_args!("{}", self));
1197 buf.shrink_to_fit();
1202 #[stable(feature = "rust1", since = "1.0.0")]
1203 impl AsRef<str> for String {
1205 fn as_ref(&self) -> &str {
1210 #[stable(feature = "rust1", since = "1.0.0")]
1211 impl AsRef<[u8]> for String {
1213 fn as_ref(&self) -> &[u8] {
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 impl<'a> From<&'a str> for String {
1222 fn from(s: &'a str) -> String {
1223 String { vec: <[_]>::to_vec(s.as_bytes()) }
1226 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1227 // required for this method definition, is not available. Since we don't
1228 // require this method for testing purposes, I'll just stub it
1229 // NB see the slice::hack module in slice.rs for more information
1232 fn from(_: &str) -> String {
1233 panic!("not available with cfg(test)");
1237 #[stable(feature = "rust1", since = "1.0.0")]
1238 impl<'a> From<&'a str> for Cow<'a, str> {
1240 fn from(s: &'a str) -> Cow<'a, str> {
1245 #[stable(feature = "rust1", since = "1.0.0")]
1246 impl<'a> From<String> for Cow<'a, str> {
1248 fn from(s: String) -> Cow<'a, str> {
1253 #[stable(feature = "rust1", since = "1.0.0")]
1254 impl Into<Vec<u8>> for String {
1255 fn into(self) -> Vec<u8> {
1260 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`",
1262 impl IntoCow<'static, str> for String {
1264 fn into_cow(self) -> Cow<'static, str> {
1269 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`",
1271 impl<'a> IntoCow<'a, str> for &'a str {
1273 fn into_cow(self) -> Cow<'a, str> {
1278 #[stable(feature = "rust1", since = "1.0.0")]
1279 impl fmt::Write for String {
1281 fn write_str(&mut self, s: &str) -> fmt::Result {
1287 fn write_char(&mut self, c: char) -> fmt::Result {
1293 /// A draining iterator for `String`.
1294 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1295 pub struct Drain<'a> {
1296 /// Will be used as &'a mut String in the destructor
1297 string: *mut String,
1298 /// Start of part to remove
1300 /// End of part to remove
1302 /// Current remaining range to remove
1306 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1307 unsafe impl<'a> Sync for Drain<'a> {}
1308 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1309 unsafe impl<'a> Send for Drain<'a> {}
1311 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1312 impl<'a> Drop for Drain<'a> {
1313 fn drop(&mut self) {
1315 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
1316 // panic code being inserted again.
1317 let self_vec = (*self.string).as_mut_vec();
1318 if self.start <= self.end && self.end <= self_vec.len() {
1319 self_vec.drain(self.start..self.end);
1325 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1326 impl<'a> Iterator for Drain<'a> {
1330 fn next(&mut self) -> Option<char> {
1334 fn size_hint(&self) -> (usize, Option<usize>) {
1335 self.iter.size_hint()
1339 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1340 impl<'a> DoubleEndedIterator for Drain<'a> {
1342 fn next_back(&mut self) -> Option<char> {
1343 self.iter.next_back()