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 // ignore-lexer-test FIXME #15679
13 //! An owned, growable string that enforces that its contents are valid UTF-8.
15 #![stable(feature = "rust1", since = "1.0.0")]
19 use core::default::Default;
20 use core::error::Error;
23 use core::iter::{IntoIterator, FromIterator};
25 use core::ops::{self, Deref, Add, Index};
28 use core::str::Pattern;
29 use unicode::str as unicode_str;
30 use unicode::str::Utf16Item;
32 use borrow::{Cow, IntoCow};
33 use str::{self, FromStr, Utf8Error};
34 use vec::{DerefVec, Vec, as_vec};
36 /// A growable string stored as a UTF-8 encoded buffer.
37 #[derive(Clone, PartialOrd, Eq, Ord)]
38 #[stable(feature = "rust1", since = "1.0.0")]
43 /// A possible error value from the `String::from_utf8` function.
44 #[stable(feature = "rust1", since = "1.0.0")]
46 pub struct FromUtf8Error {
51 /// A possible error value from the `String::from_utf16` function.
52 #[stable(feature = "rust1", since = "1.0.0")]
54 pub struct FromUtf16Error(());
57 /// Creates a new string buffer initialized with the empty string.
62 /// let mut s = String::new();
65 #[stable(feature = "rust1", since = "1.0.0")]
66 pub fn new() -> String {
72 /// Creates a new string buffer with the given capacity.
73 /// The string will be able to hold exactly `capacity` bytes without
74 /// reallocating. If `capacity` is 0, the string will not allocate.
79 /// let mut s = String::with_capacity(10);
82 #[stable(feature = "rust1", since = "1.0.0")]
83 pub fn with_capacity(capacity: usize) -> String {
85 vec: Vec::with_capacity(capacity),
89 /// Creates a new string buffer from the given string.
94 /// # #![feature(collections, core)]
95 /// let s = String::from_str("hello");
96 /// assert_eq!(s.as_slice(), "hello");
99 #[unstable(feature = "collections",
100 reason = "needs investigation to see if to_string() can match perf")]
102 pub fn from_str(string: &str) -> String {
103 String { vec: <[_]>::to_vec(string.as_bytes()) }
106 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
107 // required for this method definition, is not available. Since we don't
108 // require this method for testing purposes, I'll just stub it
109 // NB see the slice::hack module in slice.rs for more information
112 pub fn from_str(_: &str) -> String {
113 panic!("not available with cfg(test)");
116 /// Returns the vector as a string buffer, if possible, taking care not to
121 /// If the given vector is not valid UTF-8, then the original vector and the
122 /// corresponding error is returned.
127 /// # #![feature(core)]
128 /// use std::str::Utf8Error;
130 /// let hello_vec = vec![104, 101, 108, 108, 111];
131 /// let s = String::from_utf8(hello_vec).unwrap();
132 /// assert_eq!(s, "hello");
134 /// let invalid_vec = vec![240, 144, 128];
135 /// let s = String::from_utf8(invalid_vec).err().unwrap();
136 /// assert_eq!(s.utf8_error(), Utf8Error::TooShort);
137 /// assert_eq!(s.into_bytes(), [240, 144, 128]);
140 #[stable(feature = "rust1", since = "1.0.0")]
141 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
142 match str::from_utf8(&vec) {
143 Ok(..) => Ok(String { vec: vec }),
144 Err(e) => Err(FromUtf8Error { bytes: vec, error: e })
148 /// Converts a vector of bytes to a new UTF-8 string.
149 /// Any invalid UTF-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
154 /// let input = b"Hello \xF0\x90\x80World";
155 /// let output = String::from_utf8_lossy(input);
156 /// assert_eq!(output, "Hello \u{FFFD}World");
158 #[stable(feature = "rust1", since = "1.0.0")]
159 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
161 match str::from_utf8(v) {
162 Ok(s) => return Cow::Borrowed(s),
164 if let Utf8Error::InvalidByte(firstbad) = e {
170 const TAG_CONT_U8: u8 = 128;
171 const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
173 fn unsafe_get(xs: &[u8], i: usize) -> u8 {
174 unsafe { *xs.get_unchecked(i) }
176 fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 {
184 let mut res = String::with_capacity(total);
188 res.as_mut_vec().push_all(&v[..i])
192 // subseqidx is the index of the first byte of the subsequence we're looking at.
193 // It's used to copy a bunch of contiguous good codepoints at once instead of copying
195 let mut subseqidx = i;
199 let byte = unsafe_get(v, i);
202 macro_rules! error { () => ({
205 res.as_mut_vec().push_all(&v[subseqidx..i_]);
208 res.as_mut_vec().push_all(REPLACEMENT);
213 // subseqidx handles this
215 let w = unicode_str::utf8_char_width(byte);
219 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
226 match (byte, safe_get(v, i, total)) {
227 (0xE0 , 0xA0 ... 0xBF) => (),
228 (0xE1 ... 0xEC, 0x80 ... 0xBF) => (),
229 (0xED , 0x80 ... 0x9F) => (),
230 (0xEE ... 0xEF, 0x80 ... 0xBF) => (),
237 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
244 match (byte, safe_get(v, i, total)) {
245 (0xF0 , 0x90 ... 0xBF) => (),
246 (0xF1 ... 0xF3, 0x80 ... 0xBF) => (),
247 (0xF4 , 0x80 ... 0x8F) => (),
254 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
259 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
272 if subseqidx < total {
274 res.as_mut_vec().push_all(&v[subseqidx..total])
280 /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
281 /// if `v` contains any invalid data.
287 /// let mut v = &mut [0xD834, 0xDD1E, 0x006d, 0x0075,
288 /// 0x0073, 0x0069, 0x0063];
289 /// assert_eq!(String::from_utf16(v).unwrap(),
290 /// "𝄞music".to_string());
292 /// // 𝄞mu<invalid>ic
294 /// assert!(String::from_utf16(v).is_err());
296 #[stable(feature = "rust1", since = "1.0.0")]
297 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
298 let mut s = String::with_capacity(v.len());
299 for c in unicode_str::utf16_items(v) {
301 Utf16Item::ScalarValue(c) => s.push(c),
302 Utf16Item::LoneSurrogate(_) => return Err(FromUtf16Error(())),
308 /// Decode a UTF-16 encoded vector `v` into a string, replacing
309 /// invalid data with the replacement character (U+FFFD).
314 /// // 𝄞mus<invalid>ic<invalid>
315 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
316 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
319 /// assert_eq!(String::from_utf16_lossy(v),
320 /// "𝄞mus\u{FFFD}ic\u{FFFD}".to_string());
323 #[stable(feature = "rust1", since = "1.0.0")]
324 pub fn from_utf16_lossy(v: &[u16]) -> String {
325 unicode_str::utf16_items(v).map(|c| c.to_char_lossy()).collect()
328 /// Creates a new `String` from a length, capacity, and pointer.
330 /// This is unsafe because:
332 /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`;
333 /// * We assume that the `Vec` contains valid UTF-8.
335 #[stable(feature = "rust1", since = "1.0.0")]
336 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
338 vec: Vec::from_raw_parts(buf, length, capacity),
342 /// Converts a vector of bytes to a new `String` without checking if
343 /// it contains valid UTF-8. This is unsafe because it assumes that
344 /// the UTF-8-ness of the vector has already been validated.
346 #[stable(feature = "rust1", since = "1.0.0")]
347 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
348 String { vec: bytes }
351 /// Return the underlying byte buffer, encoded as UTF-8.
356 /// # #![feature(collections)]
357 /// let s = String::from_str("hello");
358 /// let bytes = s.into_bytes();
359 /// assert_eq!(bytes, [104, 101, 108, 108, 111]);
362 #[stable(feature = "rust1", since = "1.0.0")]
363 pub fn into_bytes(self) -> Vec<u8> {
367 /// Extract a string slice containing the entire string.
369 #[unstable(feature = "convert",
370 reason = "waiting on RFC revision")]
371 pub fn as_str(&self) -> &str {
375 /// Pushes the given string onto this string buffer.
380 /// # #![feature(collections)]
381 /// let mut s = String::from_str("foo");
382 /// s.push_str("bar");
383 /// assert_eq!(s, "foobar");
386 #[stable(feature = "rust1", since = "1.0.0")]
387 pub fn push_str(&mut self, string: &str) {
388 self.vec.push_all(string.as_bytes())
391 /// Returns the number of bytes that this string buffer can hold without
397 /// let s = String::with_capacity(10);
398 /// assert!(s.capacity() >= 10);
401 #[stable(feature = "rust1", since = "1.0.0")]
402 pub fn capacity(&self) -> usize {
406 /// Reserves capacity for at least `additional` more bytes to be inserted
407 /// in the given `String`. The collection may reserve more space to avoid
408 /// frequent reallocations.
412 /// Panics if the new capacity overflows `usize`.
417 /// let mut s = String::new();
419 /// assert!(s.capacity() >= 10);
422 #[stable(feature = "rust1", since = "1.0.0")]
423 pub fn reserve(&mut self, additional: usize) {
424 self.vec.reserve(additional)
427 /// Reserves the minimum capacity for exactly `additional` more bytes to be
428 /// inserted in the given `String`. Does nothing if the capacity is already
431 /// Note that the allocator may give the collection more space than it
432 /// requests. Therefore capacity can not be relied upon to be precisely
433 /// minimal. Prefer `reserve` if future insertions are expected.
437 /// Panics if the new capacity overflows `usize`.
442 /// let mut s = String::new();
444 /// assert!(s.capacity() >= 10);
447 #[stable(feature = "rust1", since = "1.0.0")]
448 pub fn reserve_exact(&mut self, additional: usize) {
449 self.vec.reserve_exact(additional)
452 /// Shrinks the capacity of this string buffer to match its length.
457 /// # #![feature(collections)]
458 /// let mut s = String::from_str("foo");
460 /// assert!(s.capacity() >= 100);
461 /// s.shrink_to_fit();
462 /// assert_eq!(s.capacity(), 3);
465 #[stable(feature = "rust1", since = "1.0.0")]
466 pub fn shrink_to_fit(&mut self) {
467 self.vec.shrink_to_fit()
470 /// Adds the given character to the end of the string.
475 /// # #![feature(collections)]
476 /// let mut s = String::from_str("abc");
480 /// assert_eq!(s, "abc123");
483 #[stable(feature = "rust1", since = "1.0.0")]
484 pub fn push(&mut self, ch: char) {
485 if (ch as u32) < 0x80 {
486 self.vec.push(ch as u8);
490 let cur_len = self.len();
491 // This may use up to 4 bytes.
495 // Attempt to not use an intermediate buffer by just pushing bytes
496 // directly onto this string.
497 let slice = slice::from_raw_parts_mut (
498 self.vec.as_mut_ptr().offset(cur_len as isize),
501 let used = ch.encode_utf8(slice).unwrap_or(0);
502 self.vec.set_len(cur_len + used);
506 /// Works with the underlying buffer as a byte slice.
511 /// # #![feature(collections)]
512 /// let s = String::from_str("hello");
513 /// let b: &[_] = &[104, 101, 108, 108, 111];
514 /// assert_eq!(s.as_bytes(), b);
517 #[stable(feature = "rust1", since = "1.0.0")]
518 pub fn as_bytes(&self) -> &[u8] {
522 /// Shortens a string to the specified length.
526 /// Panics if `new_len` > current length,
527 /// or if `new_len` is not a character boundary.
532 /// # #![feature(collections)]
533 /// let mut s = String::from_str("hello");
535 /// assert_eq!(s, "he");
538 #[stable(feature = "rust1", since = "1.0.0")]
539 pub fn truncate(&mut self, new_len: usize) {
540 assert!(self.is_char_boundary(new_len));
541 self.vec.truncate(new_len)
544 /// Removes the last character from the string buffer and returns it.
545 /// Returns `None` if this string buffer is empty.
550 /// # #![feature(collections)]
551 /// let mut s = String::from_str("foo");
552 /// assert_eq!(s.pop(), Some('o'));
553 /// assert_eq!(s.pop(), Some('o'));
554 /// assert_eq!(s.pop(), Some('f'));
555 /// assert_eq!(s.pop(), None);
558 #[stable(feature = "rust1", since = "1.0.0")]
559 pub fn pop(&mut self) -> Option<char> {
560 let len = self.len();
565 let ch = self.char_at_reverse(len);
567 self.vec.set_len(len - ch.len_utf8());
572 /// Removes the character from the string buffer at byte position `idx` and
577 /// This is an O(n) operation as it requires copying every element in the
582 /// If `idx` does not lie on a character boundary, or if it is out of
583 /// bounds, then this function will panic.
588 /// # #![feature(collections)]
589 /// let mut s = String::from_str("foo");
590 /// assert_eq!(s.remove(0), 'f');
591 /// assert_eq!(s.remove(1), 'o');
592 /// assert_eq!(s.remove(0), 'o');
595 #[stable(feature = "rust1", since = "1.0.0")]
596 pub fn remove(&mut self, idx: usize) -> char {
597 let len = self.len();
600 let ch = self.char_at(idx);
601 let next = idx + ch.len_utf8();
603 ptr::copy(self.vec.as_mut_ptr().offset(idx as isize),
604 self.vec.as_ptr().offset(next as isize),
606 self.vec.set_len(len - (next - idx));
611 /// Insert a character into the string buffer at byte position `idx`.
615 /// This is an O(n) operation as it requires copying every element in the
620 /// If `idx` does not lie on a character boundary or is out of bounds, then
621 /// this function will panic.
623 #[stable(feature = "rust1", since = "1.0.0")]
624 pub fn insert(&mut self, idx: usize, ch: char) {
625 let len = self.len();
627 assert!(self.is_char_boundary(idx));
629 let mut bits = [0; 4];
630 let amt = ch.encode_utf8(&mut bits).unwrap();
633 ptr::copy(self.vec.as_mut_ptr().offset((idx + amt) as isize),
634 self.vec.as_ptr().offset(idx as isize),
636 ptr::copy(self.vec.as_mut_ptr().offset(idx as isize),
639 self.vec.set_len(len + amt);
643 /// Views the string buffer as a mutable sequence of bytes.
645 /// This is unsafe because it does not check
646 /// to ensure that the resulting string will be valid UTF-8.
651 /// # #![feature(collections)]
652 /// let mut s = String::from_str("hello");
654 /// let vec = s.as_mut_vec();
655 /// assert!(vec == &[104, 101, 108, 108, 111]);
658 /// assert_eq!(s, "olleh");
661 #[stable(feature = "rust1", since = "1.0.0")]
662 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
666 /// Return the number of bytes in this string.
671 /// let a = "foo".to_string();
672 /// assert_eq!(a.len(), 3);
675 #[stable(feature = "rust1", since = "1.0.0")]
676 pub fn len(&self) -> usize { self.vec.len() }
678 /// Returns true if the string contains no bytes
683 /// let mut v = String::new();
684 /// assert!(v.is_empty());
686 /// assert!(!v.is_empty());
689 #[stable(feature = "rust1", since = "1.0.0")]
690 pub fn is_empty(&self) -> bool { self.len() == 0 }
692 /// Truncates the string, returning it to 0 length.
697 /// let mut s = "foo".to_string();
699 /// assert!(s.is_empty());
702 #[stable(feature = "rust1", since = "1.0.0")]
703 pub fn clear(&mut self) {
709 /// Consume this error, returning the bytes that were attempted to make a
711 #[stable(feature = "rust1", since = "1.0.0")]
712 pub fn into_bytes(self) -> Vec<u8> { self.bytes }
714 /// Access the underlying UTF8-error that was the cause of this error.
715 #[stable(feature = "rust1", since = "1.0.0")]
716 pub fn utf8_error(&self) -> Utf8Error { self.error }
719 #[stable(feature = "rust1", since = "1.0.0")]
720 impl fmt::Display for FromUtf8Error {
721 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
722 fmt::Display::fmt(&self.error, f)
726 #[stable(feature = "rust1", since = "1.0.0")]
727 impl Error for FromUtf8Error {
728 fn description(&self) -> &str { "invalid utf-8" }
731 #[stable(feature = "rust1", since = "1.0.0")]
732 impl fmt::Display for FromUtf16Error {
733 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
734 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
738 #[stable(feature = "rust1", since = "1.0.0")]
739 impl Error for FromUtf16Error {
740 fn description(&self) -> &str { "invalid utf-16" }
743 #[stable(feature = "rust1", since = "1.0.0")]
744 impl FromIterator<char> for String {
745 fn from_iter<I: IntoIterator<Item=char>>(iter: I) -> String {
746 let mut buf = String::new();
752 #[stable(feature = "rust1", since = "1.0.0")]
753 impl<'a> FromIterator<&'a str> for String {
754 fn from_iter<I: IntoIterator<Item=&'a str>>(iter: I) -> String {
755 let mut buf = String::new();
761 #[unstable(feature = "collections",
762 reason = "waiting on Extend stabilization")]
763 impl Extend<char> for String {
764 fn extend<I: IntoIterator<Item=char>>(&mut self, iterable: I) {
765 let iterator = iterable.into_iter();
766 let (lower_bound, _) = iterator.size_hint();
767 self.reserve(lower_bound);
774 #[unstable(feature = "collections",
775 reason = "waiting on Extend stabilization")]
776 impl<'a> Extend<&'a str> for String {
777 fn extend<I: IntoIterator<Item=&'a str>>(&mut self, iterable: I) {
778 let iterator = iterable.into_iter();
779 // A guess that at least one byte per iterator element will be needed.
780 let (lower_bound, _) = iterator.size_hint();
781 self.reserve(lower_bound);
788 /// A convenience impl that delegates to the impl for `&str`
789 impl<'a, 'b> Pattern<'a> for &'b String {
790 type Searcher = <&'b str as Pattern<'a>>::Searcher;
792 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
793 self[..].into_searcher(haystack)
797 fn is_contained_in(self, haystack: &'a str) -> bool {
798 self[..].is_contained_in(haystack)
802 fn is_prefix_of(self, haystack: &'a str) -> bool {
803 self[..].is_prefix_of(haystack)
807 #[stable(feature = "rust1", since = "1.0.0")]
808 impl PartialEq for String {
810 fn eq(&self, other: &String) -> bool { PartialEq::eq(&**self, &**other) }
812 fn ne(&self, other: &String) -> bool { PartialEq::ne(&**self, &**other) }
815 macro_rules! impl_eq {
816 ($lhs:ty, $rhs: ty) => {
817 #[stable(feature = "rust1", since = "1.0.0")]
818 impl<'a> PartialEq<$rhs> for $lhs {
820 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
822 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
825 #[stable(feature = "rust1", since = "1.0.0")]
826 impl<'a> PartialEq<$lhs> for $rhs {
828 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) }
830 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) }
836 impl_eq! { String, &'a str }
837 impl_eq! { Cow<'a, str>, String }
839 #[stable(feature = "rust1", since = "1.0.0")]
840 impl<'a, 'b> PartialEq<&'b str> for Cow<'a, str> {
842 fn eq(&self, other: &&'b str) -> bool { PartialEq::eq(&**self, &**other) }
844 fn ne(&self, other: &&'b str) -> bool { PartialEq::ne(&**self, &**other) }
847 #[stable(feature = "rust1", since = "1.0.0")]
848 impl<'a, 'b> PartialEq<Cow<'a, str>> for &'b str {
850 fn eq(&self, other: &Cow<'a, str>) -> bool { PartialEq::eq(&**self, &**other) }
852 fn ne(&self, other: &Cow<'a, str>) -> bool { PartialEq::ne(&**self, &**other) }
855 #[unstable(feature = "collections", reason = "waiting on Str stabilization")]
857 impl Str for String {
859 fn as_slice(&self) -> &str {
860 unsafe { mem::transmute(&*self.vec) }
864 #[stable(feature = "rust1", since = "1.0.0")]
865 impl Default for String {
867 #[stable(feature = "rust1", since = "1.0.0")]
868 fn default() -> String {
873 #[stable(feature = "rust1", since = "1.0.0")]
874 impl fmt::Display for String {
876 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
877 fmt::Display::fmt(&**self, f)
881 #[stable(feature = "rust1", since = "1.0.0")]
882 impl fmt::Debug for String {
884 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
885 fmt::Debug::fmt(&**self, f)
889 #[stable(feature = "rust1", since = "1.0.0")]
890 impl hash::Hash for String {
892 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
893 (**self).hash(hasher)
897 #[unstable(feature = "collections",
898 reason = "recent addition, needs more experience")]
899 impl<'a> Add<&'a str> for String {
900 type Output = String;
903 fn add(mut self, other: &str) -> String {
904 self.push_str(other);
909 #[stable(feature = "rust1", since = "1.0.0")]
910 impl ops::Index<ops::Range<usize>> for String {
914 fn index(&self, index: ops::Range<usize>) -> &str {
918 #[stable(feature = "rust1", since = "1.0.0")]
919 impl ops::Index<ops::RangeTo<usize>> for String {
923 fn index(&self, index: ops::RangeTo<usize>) -> &str {
927 #[stable(feature = "rust1", since = "1.0.0")]
928 impl ops::Index<ops::RangeFrom<usize>> for String {
932 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
936 #[stable(feature = "rust1", since = "1.0.0")]
937 impl ops::Index<ops::RangeFull> for String {
941 fn index(&self, _index: ops::RangeFull) -> &str {
942 unsafe { mem::transmute(&*self.vec) }
946 #[stable(feature = "rust1", since = "1.0.0")]
947 impl ops::Deref for String {
951 fn deref(&self) -> &str {
952 unsafe { mem::transmute(&self.vec[..]) }
956 /// Wrapper type providing a `&String` reference via `Deref`.
957 #[unstable(feature = "collections")]
958 pub struct DerefString<'a> {
962 impl<'a> Deref for DerefString<'a> {
963 type Target = String;
966 fn deref<'b>(&'b self) -> &'b String {
967 unsafe { mem::transmute(&*self.x) }
971 /// Convert a string slice to a wrapper type providing a `&String` reference.
976 /// # #![feature(collections)]
977 /// use std::string::as_string;
979 /// fn string_consumer(s: String) {
980 /// assert_eq!(s, "foo".to_string());
983 /// let string = as_string("foo").clone();
984 /// string_consumer(string);
986 #[unstable(feature = "collections")]
987 pub fn as_string<'a>(x: &'a str) -> DerefString<'a> {
988 DerefString { x: as_vec(x.as_bytes()) }
991 #[unstable(feature = "collections", reason = "associated error type may change")]
992 impl FromStr for String {
995 fn from_str(s: &str) -> Result<String, ()> {
996 Ok(String::from_str(s))
1000 /// A generic trait for converting a value to a string
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 pub trait ToString {
1003 /// Converts the value of `self` to an owned string
1004 #[stable(feature = "rust1", since = "1.0.0")]
1005 fn to_string(&self) -> String;
1008 #[stable(feature = "rust1", since = "1.0.0")]
1009 impl<T: fmt::Display + ?Sized> ToString for T {
1011 fn to_string(&self) -> String {
1012 use core::fmt::Write;
1013 let mut buf = String::new();
1014 let _ = buf.write_fmt(format_args!("{}", self));
1015 buf.shrink_to_fit();
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 impl AsRef<str> for String {
1022 fn as_ref(&self) -> &str {
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 impl<'a> From<&'a str> for String {
1029 fn from(s: &'a str) -> String {
1034 #[stable(feature = "rust1", since = "1.0.0")]
1035 impl Into<Vec<u8>> for String {
1036 fn into(self) -> Vec<u8> {
1041 #[stable(feature = "rust1", since = "1.0.0")]
1042 impl IntoCow<'static, str> for String {
1044 fn into_cow(self) -> Cow<'static, str> {
1049 #[stable(feature = "rust1", since = "1.0.0")]
1050 impl<'a> IntoCow<'a, str> for &'a str {
1052 fn into_cow(self) -> Cow<'a, str> {
1057 #[allow(deprecated)]
1058 impl<'a> Str for Cow<'a, str> {
1060 fn as_slice<'b>(&'b self) -> &'b str {
1065 /// A clone-on-write string
1066 #[deprecated(since = "1.0.0", reason = "use Cow<'a, str> instead")]
1067 #[stable(feature = "rust1", since = "1.0.0")]
1068 pub type CowString<'a> = Cow<'a, str>;
1070 #[stable(feature = "rust1", since = "1.0.0")]
1071 impl fmt::Write for String {
1073 fn write_str(&mut self, s: &str) -> fmt::Result {