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")]
19 use core::iter::FromIterator;
21 use core::ops::{self, Deref, Add, Index};
24 use core::str::pattern::Pattern;
25 use rustc_unicode::str as unicode_str;
26 use rustc_unicode::str::Utf16Item;
28 use borrow::{Cow, IntoCow};
29 use range::RangeArgument;
30 use str::{self, FromStr, Utf8Error, Chars};
31 use vec::{DerefVec, Vec, as_vec};
34 /// A growable string stored as a UTF-8 encoded buffer.
35 #[derive(Clone, PartialOrd, Eq, Ord)]
36 #[stable(feature = "rust1", since = "1.0.0")]
41 /// A possible error value from the `String::from_utf8` function.
42 #[stable(feature = "rust1", since = "1.0.0")]
44 pub struct FromUtf8Error {
49 /// A possible error value from the `String::from_utf16` function.
50 #[stable(feature = "rust1", since = "1.0.0")]
52 pub struct FromUtf16Error(());
55 /// Creates a new string buffer initialized with the empty string.
60 /// let mut s = String::new();
63 #[stable(feature = "rust1", since = "1.0.0")]
64 pub fn new() -> String {
70 /// Creates a new string buffer with the given capacity.
71 /// The string will be able to hold exactly `capacity` bytes without
72 /// reallocating. If `capacity` is 0, the string will not allocate.
77 /// let mut s = String::with_capacity(10);
80 #[stable(feature = "rust1", since = "1.0.0")]
81 pub fn with_capacity(capacity: usize) -> String {
83 vec: Vec::with_capacity(capacity),
87 /// Creates a new string buffer from the given string.
92 /// # #![feature(collections)]
93 /// let s = String::from("hello");
94 /// assert_eq!(&s[..], "hello");
97 #[unstable(feature = "collections", reason = "use `String::from` instead")]
98 #[deprecated(since = "1.2.0", reason = "use `String::from` instead")]
100 pub fn from_str(string: &str) -> String {
101 String { vec: <[_]>::to_vec(string.as_bytes()) }
104 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
105 // required for this method definition, is not available. Since we don't
106 // require this method for testing purposes, I'll just stub it
107 // NB see the slice::hack module in slice.rs for more information
110 pub fn from_str(_: &str) -> String {
111 panic!("not available with cfg(test)");
114 /// Returns the vector as a string buffer, if possible, taking care not to
119 /// If the given vector is not valid UTF-8, then the original vector and the
120 /// corresponding error is returned.
125 /// let hello_vec = vec![104, 101, 108, 108, 111];
126 /// let s = String::from_utf8(hello_vec).unwrap();
127 /// assert_eq!(s, "hello");
129 /// let invalid_vec = vec![240, 144, 128];
130 /// let s = String::from_utf8(invalid_vec).err().unwrap();
131 /// let err = s.utf8_error();
132 /// assert_eq!(s.into_bytes(), [240, 144, 128]);
135 #[stable(feature = "rust1", since = "1.0.0")]
136 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
137 match str::from_utf8(&vec) {
138 Ok(..) => Ok(String { vec: vec }),
139 Err(e) => Err(FromUtf8Error { bytes: vec, error: e })
143 /// Converts a vector of bytes to a new UTF-8 string.
144 /// Any invalid UTF-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
149 /// let input = b"Hello \xF0\x90\x80World";
150 /// let output = String::from_utf8_lossy(input);
151 /// assert_eq!(output, "Hello \u{FFFD}World");
153 #[stable(feature = "rust1", since = "1.0.0")]
154 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
156 match str::from_utf8(v) {
157 Ok(s) => return Cow::Borrowed(s),
158 Err(e) => i = e.valid_up_to(),
161 const TAG_CONT_U8: u8 = 128;
162 const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
164 fn unsafe_get(xs: &[u8], i: usize) -> u8 {
165 unsafe { *xs.get_unchecked(i) }
167 fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 {
175 let mut res = String::with_capacity(total);
179 res.as_mut_vec().push_all(&v[..i])
183 // subseqidx is the index of the first byte of the subsequence we're
184 // looking at. It's used to copy a bunch of contiguous good codepoints
185 // at once instead of copying them one by one.
186 let mut subseqidx = i;
190 let byte = unsafe_get(v, i);
193 macro_rules! error { () => ({
196 res.as_mut_vec().push_all(&v[subseqidx..i_]);
199 res.as_mut_vec().push_all(REPLACEMENT);
204 // subseqidx handles this
206 let w = unicode_str::utf8_char_width(byte);
210 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
217 match (byte, safe_get(v, i, total)) {
218 (0xE0 , 0xA0 ... 0xBF) => (),
219 (0xE1 ... 0xEC, 0x80 ... 0xBF) => (),
220 (0xED , 0x80 ... 0x9F) => (),
221 (0xEE ... 0xEF, 0x80 ... 0xBF) => (),
228 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
235 match (byte, safe_get(v, i, total)) {
236 (0xF0 , 0x90 ... 0xBF) => (),
237 (0xF1 ... 0xF3, 0x80 ... 0xBF) => (),
238 (0xF4 , 0x80 ... 0x8F) => (),
245 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
250 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
263 if subseqidx < total {
265 res.as_mut_vec().push_all(&v[subseqidx..total])
271 /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
272 /// if `v` contains any invalid data.
278 /// let mut v = &mut [0xD834, 0xDD1E, 0x006d, 0x0075,
279 /// 0x0073, 0x0069, 0x0063];
280 /// assert_eq!(String::from_utf16(v).unwrap(),
281 /// "𝄞music".to_string());
283 /// // 𝄞mu<invalid>ic
285 /// assert!(String::from_utf16(v).is_err());
287 #[stable(feature = "rust1", since = "1.0.0")]
288 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
289 let mut s = String::with_capacity(v.len());
290 for c in unicode_str::utf16_items(v) {
292 Utf16Item::ScalarValue(c) => s.push(c),
293 Utf16Item::LoneSurrogate(_) => return Err(FromUtf16Error(())),
299 /// Decode a UTF-16 encoded vector `v` into a string, replacing
300 /// invalid data with the replacement character (U+FFFD).
305 /// // 𝄞mus<invalid>ic<invalid>
306 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
307 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
310 /// assert_eq!(String::from_utf16_lossy(v),
311 /// "𝄞mus\u{FFFD}ic\u{FFFD}".to_string());
314 #[stable(feature = "rust1", since = "1.0.0")]
315 pub fn from_utf16_lossy(v: &[u16]) -> String {
316 unicode_str::utf16_items(v).map(|c| c.to_char_lossy()).collect()
319 /// Creates a new `String` from a length, capacity, and pointer.
323 /// This is _very_ unsafe because:
325 /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`. Therefore, this
326 /// function inherits all of its unsafety, see [its
327 /// documentation](../vec/struct.Vec.html#method.from_raw_parts)
328 /// for the invariants it expects, they also apply to this function.
329 /// * We assume that the `Vec` contains valid UTF-8.
331 #[stable(feature = "rust1", since = "1.0.0")]
332 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
334 vec: Vec::from_raw_parts(buf, length, capacity),
338 /// Converts a vector of bytes to a new `String` without checking if
339 /// it contains valid UTF-8. This is unsafe because it assumes that
340 /// the UTF-8-ness of the vector has already been validated.
342 #[stable(feature = "rust1", since = "1.0.0")]
343 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
344 String { vec: bytes }
347 /// Returns the underlying byte buffer, encoded as UTF-8.
352 /// let s = String::from("hello");
353 /// let bytes = s.into_bytes();
354 /// assert_eq!(bytes, [104, 101, 108, 108, 111]);
357 #[stable(feature = "rust1", since = "1.0.0")]
358 pub fn into_bytes(self) -> Vec<u8> {
362 /// Extracts a string slice containing the entire string.
364 #[unstable(feature = "convert",
365 reason = "waiting on RFC revision")]
366 pub fn as_str(&self) -> &str {
370 /// Pushes the given string onto this string buffer.
375 /// let mut s = String::from("foo");
376 /// s.push_str("bar");
377 /// assert_eq!(s, "foobar");
380 #[stable(feature = "rust1", since = "1.0.0")]
381 pub fn push_str(&mut self, string: &str) {
382 self.vec.push_all(string.as_bytes())
385 /// Returns the number of bytes that this string buffer can hold without
391 /// let s = String::with_capacity(10);
392 /// assert!(s.capacity() >= 10);
395 #[stable(feature = "rust1", since = "1.0.0")]
396 pub fn capacity(&self) -> usize {
400 /// Reserves capacity for at least `additional` more bytes to be inserted
401 /// in the given `String`. The collection may reserve more space to avoid
402 /// frequent reallocations.
406 /// Panics if the new capacity overflows `usize`.
411 /// let mut s = String::new();
413 /// assert!(s.capacity() >= 10);
416 #[stable(feature = "rust1", since = "1.0.0")]
417 pub fn reserve(&mut self, additional: usize) {
418 self.vec.reserve(additional)
421 /// Reserves the minimum capacity for exactly `additional` more bytes to be
422 /// inserted in the given `String`. Does nothing if the capacity is already
425 /// Note that the allocator may give the collection more space than it
426 /// requests. Therefore capacity can not be relied upon to be precisely
427 /// minimal. Prefer `reserve` if future insertions are expected.
431 /// Panics if the new capacity overflows `usize`.
436 /// let mut s = String::new();
437 /// s.reserve_exact(10);
438 /// assert!(s.capacity() >= 10);
441 #[stable(feature = "rust1", since = "1.0.0")]
442 pub fn reserve_exact(&mut self, additional: usize) {
443 self.vec.reserve_exact(additional)
446 /// Shrinks the capacity of this string buffer to match its length.
451 /// let mut s = String::from("foo");
453 /// assert!(s.capacity() >= 100);
454 /// s.shrink_to_fit();
455 /// assert_eq!(s.capacity(), 3);
458 #[stable(feature = "rust1", since = "1.0.0")]
459 pub fn shrink_to_fit(&mut self) {
460 self.vec.shrink_to_fit()
463 /// Adds the given character to the end of the string.
468 /// let mut s = String::from("abc");
472 /// assert_eq!(s, "abc123");
475 #[stable(feature = "rust1", since = "1.0.0")]
476 pub fn push(&mut self, ch: char) {
477 match ch.len_utf8() {
478 1 => self.vec.push(ch as u8),
480 let cur_len = self.len();
481 // This may use up to 4 bytes.
482 self.vec.reserve(ch_len);
485 // Attempt to not use an intermediate buffer by just pushing bytes
486 // directly onto this string.
487 let slice = slice::from_raw_parts_mut (
488 self.vec.as_mut_ptr().offset(cur_len as isize),
491 let used = ch.encode_utf8(slice).unwrap_or(0);
492 self.vec.set_len(cur_len + used);
498 /// Works with the underlying buffer as a byte slice.
503 /// let s = String::from("hello");
504 /// assert_eq!(s.as_bytes(), [104, 101, 108, 108, 111]);
507 #[stable(feature = "rust1", since = "1.0.0")]
508 pub fn as_bytes(&self) -> &[u8] {
512 /// Shortens a string to the specified length.
516 /// Panics if `new_len` > current length,
517 /// or if `new_len` is not a character boundary.
522 /// let mut s = String::from("hello");
524 /// assert_eq!(s, "he");
527 #[stable(feature = "rust1", since = "1.0.0")]
528 pub fn truncate(&mut self, new_len: usize) {
529 assert!(self.is_char_boundary(new_len));
530 self.vec.truncate(new_len)
533 /// Removes the last character from the string buffer and returns it.
534 /// Returns `None` if this string buffer is empty.
539 /// let mut s = String::from("foo");
540 /// assert_eq!(s.pop(), Some('o'));
541 /// assert_eq!(s.pop(), Some('o'));
542 /// assert_eq!(s.pop(), Some('f'));
543 /// assert_eq!(s.pop(), None);
546 #[stable(feature = "rust1", since = "1.0.0")]
547 pub fn pop(&mut self) -> Option<char> {
548 let len = self.len();
553 let ch = self.char_at_reverse(len);
555 self.vec.set_len(len - ch.len_utf8());
560 /// Removes the character from the string buffer at byte position `idx` and
565 /// This is an O(n) operation as it requires copying every element in the
570 /// If `idx` does not lie on a character boundary, or if it is out of
571 /// bounds, then this function will panic.
576 /// let mut s = String::from("foo");
577 /// assert_eq!(s.remove(0), 'f');
578 /// assert_eq!(s.remove(1), 'o');
579 /// assert_eq!(s.remove(0), 'o');
582 #[stable(feature = "rust1", since = "1.0.0")]
583 pub fn remove(&mut self, idx: usize) -> char {
584 let len = self.len();
587 let ch = self.char_at(idx);
588 let next = idx + ch.len_utf8();
590 ptr::copy(self.vec.as_ptr().offset(next as isize),
591 self.vec.as_mut_ptr().offset(idx as isize),
593 self.vec.set_len(len - (next - idx));
598 /// Inserts a character into the string buffer at byte position `idx`.
602 /// This is an O(n) operation as it requires copying every element in the
607 /// If `idx` does not lie on a character boundary or is out of bounds, then
608 /// this function will panic.
610 #[stable(feature = "rust1", since = "1.0.0")]
611 pub fn insert(&mut self, idx: usize, ch: char) {
612 let len = self.len();
614 assert!(self.is_char_boundary(idx));
616 let mut bits = [0; 4];
617 let amt = ch.encode_utf8(&mut bits).unwrap();
620 ptr::copy(self.vec.as_ptr().offset(idx as isize),
621 self.vec.as_mut_ptr().offset((idx + amt) as isize),
623 ptr::copy(bits.as_ptr(),
624 self.vec.as_mut_ptr().offset(idx as isize),
626 self.vec.set_len(len + amt);
630 /// Views the string buffer as a mutable sequence of bytes.
632 /// This is unsafe because it does not check
633 /// to ensure that the resulting string will be valid UTF-8.
638 /// let mut s = String::from("hello");
640 /// let vec = s.as_mut_vec();
641 /// assert!(vec == &[104, 101, 108, 108, 111]);
644 /// assert_eq!(s, "olleh");
647 #[stable(feature = "rust1", since = "1.0.0")]
648 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
652 /// Returns the number of bytes in this string.
657 /// let a = "foo".to_string();
658 /// assert_eq!(a.len(), 3);
661 #[stable(feature = "rust1", since = "1.0.0")]
662 pub fn len(&self) -> usize { self.vec.len() }
664 /// Returns true if the string contains no bytes
669 /// let mut v = String::new();
670 /// assert!(v.is_empty());
672 /// assert!(!v.is_empty());
675 #[stable(feature = "rust1", since = "1.0.0")]
676 pub fn is_empty(&self) -> bool { self.len() == 0 }
678 /// Truncates the string, returning it to 0 length.
683 /// let mut s = "foo".to_string();
685 /// assert!(s.is_empty());
688 #[stable(feature = "rust1", since = "1.0.0")]
689 pub fn clear(&mut self) {
693 /// Create a draining iterator that removes the specified range in the string
694 /// and yields the removed chars from start to end. The element range is
695 /// removed even if the iterator is not consumed until the end.
699 /// Panics if the starting point or end point are not on character boundaries,
700 /// or if they are out of bounds.
705 /// # #![feature(drain)]
707 /// let mut s = String::from("α is alpha, β is beta");
708 /// let beta_offset = s.find('β').unwrap_or(s.len());
710 /// // Remove the range up until the β from the string
711 /// let t: String = s.drain(..beta_offset).collect();
712 /// assert_eq!(t, "α is alpha, ");
713 /// assert_eq!(s, "β is beta");
715 /// // A full range clears the string
717 /// assert_eq!(s, "");
719 #[unstable(feature = "drain",
720 reason = "recently added, matches RFC")]
721 pub fn drain<R>(&mut self, range: R) -> Drain where R: RangeArgument<usize> {
724 // The String version of Drain does not have the memory safety issues
725 // of the vector version. The data is just plain bytes.
726 // Because the range removal happens in Drop, if the Drain iterator is leaked,
727 // the removal will not happen.
728 let len = self.len();
729 let start = *range.start().unwrap_or(&0);
730 let end = *range.end().unwrap_or(&len);
732 // Take out two simultaneous borrows. The &mut String won't be accessed
733 // until iteration is over, in Drop.
734 let self_ptr = self as *mut _;
735 // slicing does the appropriate bounds checks
736 let chars_iter = self[start..end].chars();
746 /// Converts the string into `Box<str>`.
748 /// Note that this will drop any excess capacity.
749 #[unstable(feature = "box_str",
750 reason = "recently added, matches RFC")]
751 pub fn into_boxed_slice(self) -> Box<str> {
752 let slice = self.vec.into_boxed_slice();
753 unsafe { mem::transmute::<Box<[u8]>, Box<str>>(slice) }
758 /// Consumes this error, returning the bytes that were attempted to make a
760 #[stable(feature = "rust1", since = "1.0.0")]
761 pub fn into_bytes(self) -> Vec<u8> { self.bytes }
763 /// Access the underlying UTF8-error that was the cause of this error.
764 #[stable(feature = "rust1", since = "1.0.0")]
765 pub fn utf8_error(&self) -> Utf8Error { self.error }
768 #[stable(feature = "rust1", since = "1.0.0")]
769 impl fmt::Display for FromUtf8Error {
770 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
771 fmt::Display::fmt(&self.error, f)
775 #[stable(feature = "rust1", since = "1.0.0")]
776 impl fmt::Display for FromUtf16Error {
777 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
778 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
782 #[stable(feature = "rust1", since = "1.0.0")]
783 impl FromIterator<char> for String {
784 fn from_iter<I: IntoIterator<Item=char>>(iter: I) -> String {
785 let mut buf = String::new();
791 #[stable(feature = "rust1", since = "1.0.0")]
792 impl<'a> FromIterator<&'a str> for String {
793 fn from_iter<I: IntoIterator<Item=&'a str>>(iter: I) -> String {
794 let mut buf = String::new();
800 #[stable(feature = "rust1", since = "1.0.0")]
801 impl Extend<char> for String {
802 fn extend<I: IntoIterator<Item=char>>(&mut self, iterable: I) {
803 let iterator = iterable.into_iter();
804 let (lower_bound, _) = iterator.size_hint();
805 self.reserve(lower_bound);
812 #[stable(feature = "extend_ref", since = "1.2.0")]
813 impl<'a> Extend<&'a char> for String {
814 fn extend<I: IntoIterator<Item=&'a char>>(&mut self, iter: I) {
815 self.extend(iter.into_iter().cloned());
819 #[stable(feature = "rust1", since = "1.0.0")]
820 impl<'a> Extend<&'a str> for String {
821 fn extend<I: IntoIterator<Item=&'a str>>(&mut self, iterable: I) {
822 let iterator = iterable.into_iter();
823 // A guess that at least one byte per iterator element will be needed.
824 let (lower_bound, _) = iterator.size_hint();
825 self.reserve(lower_bound);
832 /// A convenience impl that delegates to the impl for `&str`
833 impl<'a, 'b> Pattern<'a> for &'b String {
834 type Searcher = <&'b str as Pattern<'a>>::Searcher;
836 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
837 self[..].into_searcher(haystack)
841 fn is_contained_in(self, haystack: &'a str) -> bool {
842 self[..].is_contained_in(haystack)
846 fn is_prefix_of(self, haystack: &'a str) -> bool {
847 self[..].is_prefix_of(haystack)
851 #[stable(feature = "rust1", since = "1.0.0")]
852 impl PartialEq for String {
854 fn eq(&self, other: &String) -> bool { PartialEq::eq(&self[..], &other[..]) }
856 fn ne(&self, other: &String) -> bool { PartialEq::ne(&self[..], &other[..]) }
859 macro_rules! impl_eq {
860 ($lhs:ty, $rhs: ty) => {
861 #[stable(feature = "rust1", since = "1.0.0")]
862 impl<'a> PartialEq<$rhs> for $lhs {
864 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
866 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
869 #[stable(feature = "rust1", since = "1.0.0")]
870 impl<'a> PartialEq<$lhs> for $rhs {
872 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
874 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
880 impl_eq! { String, str }
881 impl_eq! { String, &'a str }
882 impl_eq! { Cow<'a, str>, str }
883 impl_eq! { Cow<'a, str>, String }
885 #[stable(feature = "rust1", since = "1.0.0")]
886 impl<'a, 'b> PartialEq<&'b str> for Cow<'a, str> {
888 fn eq(&self, other: &&'b str) -> bool { PartialEq::eq(&self[..], &other[..]) }
890 fn ne(&self, other: &&'b str) -> bool { PartialEq::ne(&self[..], &other[..]) }
893 #[stable(feature = "rust1", since = "1.0.0")]
894 impl<'a, 'b> PartialEq<Cow<'a, str>> for &'b str {
896 fn eq(&self, other: &Cow<'a, str>) -> bool { PartialEq::eq(&self[..], &other[..]) }
898 fn ne(&self, other: &Cow<'a, str>) -> bool { PartialEq::ne(&self[..], &other[..]) }
901 #[stable(feature = "rust1", since = "1.0.0")]
902 impl Default for String {
904 #[stable(feature = "rust1", since = "1.0.0")]
905 fn default() -> String {
910 #[stable(feature = "rust1", since = "1.0.0")]
911 impl fmt::Display for String {
913 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
914 fmt::Display::fmt(&**self, f)
918 #[stable(feature = "rust1", since = "1.0.0")]
919 impl fmt::Debug for String {
921 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
922 fmt::Debug::fmt(&**self, f)
926 #[stable(feature = "rust1", since = "1.0.0")]
927 impl hash::Hash for String {
929 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
930 (**self).hash(hasher)
934 #[stable(feature = "rust1", since = "1.0.0")]
935 impl<'a> Add<&'a str> for String {
936 type Output = String;
939 fn add(mut self, other: &str) -> String {
940 self.push_str(other);
945 #[stable(feature = "rust1", since = "1.0.0")]
946 impl ops::Index<ops::Range<usize>> for String {
950 fn index(&self, index: ops::Range<usize>) -> &str {
954 #[stable(feature = "rust1", since = "1.0.0")]
955 impl ops::Index<ops::RangeTo<usize>> for String {
959 fn index(&self, index: ops::RangeTo<usize>) -> &str {
963 #[stable(feature = "rust1", since = "1.0.0")]
964 impl ops::Index<ops::RangeFrom<usize>> for String {
968 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
972 #[stable(feature = "rust1", since = "1.0.0")]
973 impl ops::Index<ops::RangeFull> for String {
977 fn index(&self, _index: ops::RangeFull) -> &str {
978 unsafe { mem::transmute(&*self.vec) }
982 #[stable(feature = "rust1", since = "1.0.0")]
983 impl ops::Deref for String {
987 fn deref(&self) -> &str {
988 unsafe { mem::transmute(&self.vec[..]) }
992 /// Wrapper type providing a `&String` reference via `Deref`.
993 #[unstable(feature = "collections")]
994 #[deprecated(since = "1.2.0",
995 reason = "replaced with deref coercions or Borrow")]
997 pub struct DerefString<'a> {
1001 #[allow(deprecated)]
1002 impl<'a> Deref for DerefString<'a> {
1003 type Target = String;
1006 fn deref<'b>(&'b self) -> &'b String {
1007 unsafe { mem::transmute(&*self.x) }
1011 /// Converts a string slice to a wrapper type providing a `&String` reference.
1016 /// # #![feature(collections)]
1017 /// use std::string::as_string;
1019 /// // Let's pretend we have a function that requires `&String`
1020 /// fn string_consumer(s: &String) {
1021 /// assert_eq!(s, "foo");
1024 /// // Provide a `&String` from a `&str` without allocating
1025 /// string_consumer(&as_string("foo"));
1027 #[unstable(feature = "collections")]
1028 #[deprecated(since = "1.2.0",
1029 reason = "replaced with deref coercions or Borrow")]
1030 #[allow(deprecated)]
1031 pub fn as_string<'a>(x: &'a str) -> DerefString<'a> {
1032 DerefString { x: as_vec(x.as_bytes()) }
1035 /// Error returned from `String::from`
1036 #[unstable(feature = "str_parse_error", reason = "may want to be replaced with \
1037 Void if it ever exists")]
1038 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1039 pub struct ParseError(());
1041 #[stable(feature = "rust1", since = "1.0.0")]
1042 impl FromStr for String {
1043 type Err = ParseError;
1045 fn from_str(s: &str) -> Result<String, ParseError> {
1050 /// A generic trait for converting a value to a string
1051 #[stable(feature = "rust1", since = "1.0.0")]
1052 pub trait ToString {
1053 /// Converts the value of `self` to an owned string
1054 #[stable(feature = "rust1", since = "1.0.0")]
1055 fn to_string(&self) -> String;
1058 #[stable(feature = "rust1", since = "1.0.0")]
1059 impl<T: fmt::Display + ?Sized> ToString for T {
1061 fn to_string(&self) -> String {
1062 use core::fmt::Write;
1063 let mut buf = String::new();
1064 let _ = buf.write_fmt(format_args!("{}", self));
1065 buf.shrink_to_fit();
1070 #[stable(feature = "rust1", since = "1.0.0")]
1071 impl AsRef<str> for String {
1073 fn as_ref(&self) -> &str {
1078 #[stable(feature = "rust1", since = "1.0.0")]
1079 impl AsRef<[u8]> for String {
1081 fn as_ref(&self) -> &[u8] {
1086 #[stable(feature = "rust1", since = "1.0.0")]
1087 impl<'a> From<&'a str> for String {
1090 fn from(s: &'a str) -> String {
1091 String { vec: <[_]>::to_vec(s.as_bytes()) }
1094 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1095 // required for this method definition, is not available. Since we don't
1096 // require this method for testing purposes, I'll just stub it
1097 // NB see the slice::hack module in slice.rs for more information
1100 fn from(_: &str) -> String {
1101 panic!("not available with cfg(test)");
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 impl<'a> From<&'a str> for Cow<'a, str> {
1108 fn from(s: &'a str) -> Cow<'a, str> {
1113 #[stable(feature = "rust1", since = "1.0.0")]
1114 impl<'a> From<String> for Cow<'a, str> {
1116 fn from(s: String) -> Cow<'a, str> {
1121 #[stable(feature = "rust1", since = "1.0.0")]
1122 impl Into<Vec<u8>> for String {
1123 fn into(self) -> Vec<u8> {
1128 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`")]
1129 impl IntoCow<'static, str> for String {
1131 fn into_cow(self) -> Cow<'static, str> {
1136 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`")]
1137 impl<'a> IntoCow<'a, str> for &'a str {
1139 fn into_cow(self) -> Cow<'a, str> {
1144 #[stable(feature = "rust1", since = "1.0.0")]
1145 impl fmt::Write for String {
1147 fn write_str(&mut self, s: &str) -> fmt::Result {
1153 fn write_char(&mut self, c: char) -> fmt::Result {
1159 /// A draining iterator for `String`.
1160 #[unstable(feature = "drain", reason = "recently added")]
1161 pub struct Drain<'a> {
1162 /// Will be used as &'a mut String in the destructor
1163 string: *mut String,
1164 /// Start of part to remove
1166 /// End of part to remove
1168 /// Current remaining range to remove
1172 unsafe impl<'a> Sync for Drain<'a> {}
1173 unsafe impl<'a> Send for Drain<'a> {}
1175 #[unstable(feature = "drain", reason = "recently added")]
1176 impl<'a> Drop for Drain<'a> {
1177 fn drop(&mut self) {
1179 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
1180 // panic code being inserted again.
1181 let self_vec = (*self.string).as_mut_vec();
1182 if self.start <= self.end && self.end <= self_vec.len() {
1183 self_vec.drain(self.start..self.end);
1189 #[unstable(feature = "drain", reason = "recently added")]
1190 impl<'a> Iterator for Drain<'a> {
1194 fn next(&mut self) -> Option<char> {
1198 fn size_hint(&self) -> (usize, Option<usize>) {
1199 self.iter.size_hint()
1203 #[unstable(feature = "drain", reason = "recently added")]
1204 impl<'a> DoubleEndedIterator for Drain<'a> {
1206 fn next_back(&mut self) -> Option<char> {
1207 self.iter.next_back()