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 /// Pushes the given string onto this string buffer.
372 /// # #![feature(collections)]
373 /// let mut s = String::from_str("foo");
374 /// s.push_str("bar");
375 /// assert_eq!(s, "foobar");
378 #[stable(feature = "rust1", since = "1.0.0")]
379 pub fn push_str(&mut self, string: &str) {
380 self.vec.push_all(string.as_bytes())
383 /// Returns the number of bytes that this string buffer can hold without
389 /// let s = String::with_capacity(10);
390 /// assert!(s.capacity() >= 10);
393 #[stable(feature = "rust1", since = "1.0.0")]
394 pub fn capacity(&self) -> usize {
398 /// Reserves capacity for at least `additional` more bytes to be inserted
399 /// in the given `String`. The collection may reserve more space to avoid
400 /// frequent reallocations.
404 /// Panics if the new capacity overflows `usize`.
409 /// let mut s = String::new();
411 /// assert!(s.capacity() >= 10);
414 #[stable(feature = "rust1", since = "1.0.0")]
415 pub fn reserve(&mut self, additional: usize) {
416 self.vec.reserve(additional)
419 /// Reserves the minimum capacity for exactly `additional` more bytes to be
420 /// inserted in the given `String`. Does nothing if the capacity is already
423 /// Note that the allocator may give the collection more space than it
424 /// requests. Therefore capacity can not be relied upon to be precisely
425 /// minimal. Prefer `reserve` if future insertions are expected.
429 /// Panics if the new capacity overflows `usize`.
434 /// let mut s = String::new();
436 /// assert!(s.capacity() >= 10);
439 #[stable(feature = "rust1", since = "1.0.0")]
440 pub fn reserve_exact(&mut self, additional: usize) {
441 self.vec.reserve_exact(additional)
444 /// Shrinks the capacity of this string buffer to match its length.
449 /// # #![feature(collections)]
450 /// let mut s = String::from_str("foo");
452 /// assert!(s.capacity() >= 100);
453 /// s.shrink_to_fit();
454 /// assert_eq!(s.capacity(), 3);
457 #[stable(feature = "rust1", since = "1.0.0")]
458 pub fn shrink_to_fit(&mut self) {
459 self.vec.shrink_to_fit()
462 /// Adds the given character to the end of the string.
467 /// # #![feature(collections)]
468 /// let mut s = String::from_str("abc");
472 /// assert_eq!(s, "abc123");
475 #[stable(feature = "rust1", since = "1.0.0")]
476 pub fn push(&mut self, ch: char) {
477 if (ch as u32) < 0x80 {
478 self.vec.push(ch as u8);
482 let cur_len = self.len();
483 // This may use up to 4 bytes.
487 // Attempt to not use an intermediate buffer by just pushing bytes
488 // directly onto this string.
489 let slice = slice::from_raw_parts_mut (
490 self.vec.as_mut_ptr().offset(cur_len as isize),
493 let used = ch.encode_utf8(slice).unwrap_or(0);
494 self.vec.set_len(cur_len + used);
498 /// Works with the underlying buffer as a byte slice.
503 /// # #![feature(collections)]
504 /// let s = String::from_str("hello");
505 /// let b: &[_] = &[104, 101, 108, 108, 111];
506 /// assert_eq!(s.as_bytes(), b);
509 #[stable(feature = "rust1", since = "1.0.0")]
510 pub fn as_bytes(&self) -> &[u8] {
514 /// Shortens a string to the specified length.
518 /// Panics if `new_len` > current length,
519 /// or if `new_len` is not a character boundary.
524 /// # #![feature(collections)]
525 /// let mut s = String::from_str("hello");
527 /// assert_eq!(s, "he");
530 #[stable(feature = "rust1", since = "1.0.0")]
531 pub fn truncate(&mut self, new_len: usize) {
532 assert!(self.is_char_boundary(new_len));
533 self.vec.truncate(new_len)
536 /// Removes the last character from the string buffer and returns it.
537 /// Returns `None` if this string buffer is empty.
542 /// # #![feature(collections)]
543 /// let mut s = String::from_str("foo");
544 /// assert_eq!(s.pop(), Some('o'));
545 /// assert_eq!(s.pop(), Some('o'));
546 /// assert_eq!(s.pop(), Some('f'));
547 /// assert_eq!(s.pop(), None);
550 #[stable(feature = "rust1", since = "1.0.0")]
551 pub fn pop(&mut self) -> Option<char> {
552 let len = self.len();
557 let ch = self.char_at_reverse(len);
559 self.vec.set_len(len - ch.len_utf8());
564 /// Removes the character from the string buffer at byte position `idx` and
569 /// This is an O(n) operation as it requires copying every element in the
574 /// If `idx` does not lie on a character boundary, or if it is out of
575 /// bounds, then this function will panic.
580 /// # #![feature(collections)]
581 /// let mut s = String::from_str("foo");
582 /// assert_eq!(s.remove(0), 'f');
583 /// assert_eq!(s.remove(1), 'o');
584 /// assert_eq!(s.remove(0), 'o');
587 #[stable(feature = "rust1", since = "1.0.0")]
588 pub fn remove(&mut self, idx: usize) -> char {
589 let len = self.len();
592 let ch = self.char_at(idx);
593 let next = idx + ch.len_utf8();
595 ptr::copy(self.vec.as_mut_ptr().offset(idx as isize),
596 self.vec.as_ptr().offset(next as isize),
598 self.vec.set_len(len - (next - idx));
603 /// Insert a character into the string buffer at byte position `idx`.
607 /// This is an O(n) operation as it requires copying every element in the
612 /// If `idx` does not lie on a character boundary or is out of bounds, then
613 /// this function will panic.
615 #[stable(feature = "rust1", since = "1.0.0")]
616 pub fn insert(&mut self, idx: usize, ch: char) {
617 let len = self.len();
619 assert!(self.is_char_boundary(idx));
621 let mut bits = [0; 4];
622 let amt = ch.encode_utf8(&mut bits).unwrap();
625 ptr::copy(self.vec.as_mut_ptr().offset((idx + amt) as isize),
626 self.vec.as_ptr().offset(idx as isize),
628 ptr::copy(self.vec.as_mut_ptr().offset(idx as isize),
631 self.vec.set_len(len + amt);
635 /// Views the string buffer as a mutable sequence of bytes.
637 /// This is unsafe because it does not check
638 /// to ensure that the resulting string will be valid UTF-8.
643 /// # #![feature(collections)]
644 /// let mut s = String::from_str("hello");
646 /// let vec = s.as_mut_vec();
647 /// assert!(vec == &[104, 101, 108, 108, 111]);
650 /// assert_eq!(s, "olleh");
653 #[stable(feature = "rust1", since = "1.0.0")]
654 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
658 /// Return the number of bytes in this string.
663 /// let a = "foo".to_string();
664 /// assert_eq!(a.len(), 3);
667 #[stable(feature = "rust1", since = "1.0.0")]
668 pub fn len(&self) -> usize { self.vec.len() }
670 /// Returns true if the string contains no bytes
675 /// let mut v = String::new();
676 /// assert!(v.is_empty());
678 /// assert!(!v.is_empty());
681 #[stable(feature = "rust1", since = "1.0.0")]
682 pub fn is_empty(&self) -> bool { self.len() == 0 }
684 /// Truncates the string, returning it to 0 length.
689 /// let mut s = "foo".to_string();
691 /// assert!(s.is_empty());
694 #[stable(feature = "rust1", since = "1.0.0")]
695 pub fn clear(&mut self) {
701 /// Consume this error, returning the bytes that were attempted to make a
703 #[stable(feature = "rust1", since = "1.0.0")]
704 pub fn into_bytes(self) -> Vec<u8> { self.bytes }
706 /// Access the underlying UTF8-error that was the cause of this error.
707 #[stable(feature = "rust1", since = "1.0.0")]
708 pub fn utf8_error(&self) -> Utf8Error { self.error }
711 #[stable(feature = "rust1", since = "1.0.0")]
712 impl fmt::Display for FromUtf8Error {
713 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
714 fmt::Display::fmt(&self.error, f)
718 #[stable(feature = "rust1", since = "1.0.0")]
719 impl Error for FromUtf8Error {
720 fn description(&self) -> &str { "invalid utf-8" }
723 #[stable(feature = "rust1", since = "1.0.0")]
724 impl fmt::Display for FromUtf16Error {
725 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
726 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
730 #[stable(feature = "rust1", since = "1.0.0")]
731 impl Error for FromUtf16Error {
732 fn description(&self) -> &str { "invalid utf-16" }
735 #[stable(feature = "rust1", since = "1.0.0")]
736 impl FromIterator<char> for String {
737 fn from_iter<I: IntoIterator<Item=char>>(iter: I) -> String {
738 let mut buf = String::new();
744 #[stable(feature = "rust1", since = "1.0.0")]
745 impl<'a> FromIterator<&'a str> for String {
746 fn from_iter<I: IntoIterator<Item=&'a str>>(iter: I) -> String {
747 let mut buf = String::new();
753 #[unstable(feature = "collections",
754 reason = "waiting on Extend stabilization")]
755 impl Extend<char> for String {
756 fn extend<I: IntoIterator<Item=char>>(&mut self, iterable: I) {
757 let iterator = iterable.into_iter();
758 let (lower_bound, _) = iterator.size_hint();
759 self.reserve(lower_bound);
766 #[unstable(feature = "collections",
767 reason = "waiting on Extend stabilization")]
768 impl<'a> Extend<&'a str> for String {
769 fn extend<I: IntoIterator<Item=&'a str>>(&mut self, iterable: I) {
770 let iterator = iterable.into_iter();
771 // A guess that at least one byte per iterator element will be needed.
772 let (lower_bound, _) = iterator.size_hint();
773 self.reserve(lower_bound);
780 /// A convenience impl that delegates to the impl for `&str`
781 impl<'a, 'b> Pattern<'a> for &'b String {
782 type Searcher = <&'b str as Pattern<'a>>::Searcher;
784 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
785 self[..].into_searcher(haystack)
789 fn is_contained_in(self, haystack: &'a str) -> bool {
790 self[..].is_contained_in(haystack)
794 fn is_prefix_of(self, haystack: &'a str) -> bool {
795 self[..].is_prefix_of(haystack)
799 #[stable(feature = "rust1", since = "1.0.0")]
800 impl PartialEq for String {
802 fn eq(&self, other: &String) -> bool { PartialEq::eq(&**self, &**other) }
804 fn ne(&self, other: &String) -> bool { PartialEq::ne(&**self, &**other) }
807 macro_rules! impl_eq {
808 ($lhs:ty, $rhs: ty) => {
809 #[stable(feature = "rust1", since = "1.0.0")]
810 impl<'a> PartialEq<$rhs> for $lhs {
812 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
814 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
817 #[stable(feature = "rust1", since = "1.0.0")]
818 impl<'a> PartialEq<$lhs> for $rhs {
820 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) }
822 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) }
828 impl_eq! { String, &'a str }
829 impl_eq! { Cow<'a, str>, String }
831 #[stable(feature = "rust1", since = "1.0.0")]
832 impl<'a, 'b> PartialEq<&'b str> for Cow<'a, str> {
834 fn eq(&self, other: &&'b str) -> bool { PartialEq::eq(&**self, &**other) }
836 fn ne(&self, other: &&'b str) -> bool { PartialEq::ne(&**self, &**other) }
839 #[stable(feature = "rust1", since = "1.0.0")]
840 impl<'a, 'b> PartialEq<Cow<'a, str>> for &'b str {
842 fn eq(&self, other: &Cow<'a, str>) -> bool { PartialEq::eq(&**self, &**other) }
844 fn ne(&self, other: &Cow<'a, str>) -> bool { PartialEq::ne(&**self, &**other) }
847 #[unstable(feature = "collections", reason = "waiting on Str stabilization")]
849 impl Str for String {
851 #[stable(feature = "rust1", since = "1.0.0")]
852 fn as_slice(&self) -> &str {
853 unsafe { mem::transmute(&*self.vec) }
857 #[stable(feature = "rust1", since = "1.0.0")]
858 impl Default for String {
860 #[stable(feature = "rust1", since = "1.0.0")]
861 fn default() -> String {
866 #[stable(feature = "rust1", since = "1.0.0")]
867 impl fmt::Display for String {
869 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
870 fmt::Display::fmt(&**self, f)
874 #[stable(feature = "rust1", since = "1.0.0")]
875 impl fmt::Debug for String {
877 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
878 fmt::Debug::fmt(&**self, f)
882 #[stable(feature = "rust1", since = "1.0.0")]
883 impl hash::Hash for String {
885 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
886 (**self).hash(hasher)
890 #[unstable(feature = "collections",
891 reason = "recent addition, needs more experience")]
892 impl<'a> Add<&'a str> for String {
893 type Output = String;
896 fn add(mut self, other: &str) -> String {
897 self.push_str(other);
902 #[stable(feature = "rust1", since = "1.0.0")]
903 impl ops::Index<ops::Range<usize>> for String {
907 fn index(&self, index: ops::Range<usize>) -> &str {
911 #[stable(feature = "rust1", since = "1.0.0")]
912 impl ops::Index<ops::RangeTo<usize>> for String {
916 fn index(&self, index: ops::RangeTo<usize>) -> &str {
920 #[stable(feature = "rust1", since = "1.0.0")]
921 impl ops::Index<ops::RangeFrom<usize>> for String {
925 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
929 #[stable(feature = "rust1", since = "1.0.0")]
930 impl ops::Index<ops::RangeFull> for String {
934 fn index(&self, _index: ops::RangeFull) -> &str {
935 unsafe { mem::transmute(&*self.vec) }
939 #[stable(feature = "rust1", since = "1.0.0")]
940 impl ops::Deref for String {
944 fn deref(&self) -> &str {
945 unsafe { mem::transmute(&self.vec[..]) }
949 /// Wrapper type providing a `&String` reference via `Deref`.
950 #[unstable(feature = "collections")]
951 pub struct DerefString<'a> {
955 impl<'a> Deref for DerefString<'a> {
956 type Target = String;
959 fn deref<'b>(&'b self) -> &'b String {
960 unsafe { mem::transmute(&*self.x) }
964 /// Convert a string slice to a wrapper type providing a `&String` reference.
969 /// # #![feature(collections)]
970 /// use std::string::as_string;
972 /// fn string_consumer(s: String) {
973 /// assert_eq!(s, "foo".to_string());
976 /// let string = as_string("foo").clone();
977 /// string_consumer(string);
979 #[unstable(feature = "collections")]
980 pub fn as_string<'a>(x: &'a str) -> DerefString<'a> {
981 DerefString { x: as_vec(x.as_bytes()) }
984 #[unstable(feature = "collections", reason = "associated error type may change")]
985 impl FromStr for String {
988 fn from_str(s: &str) -> Result<String, ()> {
989 Ok(String::from_str(s))
993 /// A generic trait for converting a value to a string
994 #[stable(feature = "rust1", since = "1.0.0")]
996 /// Converts the value of `self` to an owned string
997 #[stable(feature = "rust1", since = "1.0.0")]
998 fn to_string(&self) -> String;
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 impl<T: fmt::Display + ?Sized> ToString for T {
1004 fn to_string(&self) -> String {
1005 use core::fmt::Write;
1006 let mut buf = String::new();
1007 let _ = buf.write_fmt(format_args!("{}", self));
1008 buf.shrink_to_fit();
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 impl AsRef<str> for String {
1015 fn as_ref(&self) -> &str {
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 impl<'a> From<&'a str> for String {
1022 fn from(s: &'a str) -> String {
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 impl Into<Vec<u8>> for String {
1029 fn into(self) -> Vec<u8> {
1034 #[stable(feature = "rust1", since = "1.0.0")]
1035 impl IntoCow<'static, str> for String {
1037 fn into_cow(self) -> Cow<'static, str> {
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 impl<'a> IntoCow<'a, str> for &'a str {
1045 fn into_cow(self) -> Cow<'a, str> {
1050 #[allow(deprecated)]
1051 impl<'a> Str for Cow<'a, str> {
1053 fn as_slice<'b>(&'b self) -> &'b str {
1058 /// A clone-on-write string
1059 #[deprecated(since = "1.0.0", reason = "use Cow<'a, str> instead")]
1060 #[stable(feature = "rust1", since = "1.0.0")]
1061 pub type CowString<'a> = Cow<'a, str>;
1063 #[stable(feature = "rust1", since = "1.0.0")]
1064 impl fmt::Write for String {
1066 fn write_str(&mut self, s: &str) -> fmt::Result {