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};
33 /// A growable string stored as a UTF-8 encoded buffer.
34 #[derive(Clone, PartialOrd, Eq, Ord)]
35 #[stable(feature = "rust1", since = "1.0.0")]
40 /// A possible error value from the `String::from_utf8` function.
41 #[stable(feature = "rust1", since = "1.0.0")]
43 pub struct FromUtf8Error {
48 /// A possible error value from the `String::from_utf16` function.
49 #[stable(feature = "rust1", since = "1.0.0")]
51 pub struct FromUtf16Error(());
54 /// Creates a new string buffer initialized with the empty string.
59 /// let mut s = String::new();
62 #[stable(feature = "rust1", since = "1.0.0")]
63 pub fn new() -> String {
69 /// Creates a new string buffer with the given capacity.
70 /// The string will be able to hold exactly `capacity` bytes without
71 /// reallocating. If `capacity` is 0, the string will not allocate.
76 /// let mut s = String::with_capacity(10);
79 #[stable(feature = "rust1", since = "1.0.0")]
80 pub fn with_capacity(capacity: usize) -> String {
82 vec: Vec::with_capacity(capacity),
86 /// Creates a new string buffer from the given string.
91 /// # #![feature(collections)]
92 /// let s = String::from("hello");
93 /// assert_eq!(&s[..], "hello");
96 #[unstable(feature = "collections", reason = "use `String::from` instead")]
97 #[deprecated(since = "1.2.0", reason = "use `String::from` instead")]
99 pub fn from_str(string: &str) -> String {
100 String { vec: <[_]>::to_vec(string.as_bytes()) }
103 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
104 // required for this method definition, is not available. Since we don't
105 // require this method for testing purposes, I'll just stub it
106 // NB see the slice::hack module in slice.rs for more information
109 pub fn from_str(_: &str) -> String {
110 panic!("not available with cfg(test)");
113 /// Returns the vector as a string buffer, if possible, taking care not to
118 /// If the given vector is not valid UTF-8, then the original vector and the
119 /// corresponding error is returned.
124 /// let hello_vec = vec![104, 101, 108, 108, 111];
125 /// let s = String::from_utf8(hello_vec).unwrap();
126 /// assert_eq!(s, "hello");
128 /// let invalid_vec = vec![240, 144, 128];
129 /// let s = String::from_utf8(invalid_vec).err().unwrap();
130 /// let err = s.utf8_error();
131 /// assert_eq!(s.into_bytes(), [240, 144, 128]);
134 #[stable(feature = "rust1", since = "1.0.0")]
135 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
136 match str::from_utf8(&vec) {
137 Ok(..) => Ok(String { vec: vec }),
138 Err(e) => Err(FromUtf8Error { bytes: vec, error: e })
142 /// Converts a vector of bytes to a new UTF-8 string.
143 /// Any invalid UTF-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
148 /// let input = b"Hello \xF0\x90\x80World";
149 /// let output = String::from_utf8_lossy(input);
150 /// assert_eq!(output, "Hello \u{FFFD}World");
152 #[stable(feature = "rust1", since = "1.0.0")]
153 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
155 match str::from_utf8(v) {
156 Ok(s) => return Cow::Borrowed(s),
157 Err(e) => i = e.valid_up_to(),
160 const TAG_CONT_U8: u8 = 128;
161 const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
163 fn unsafe_get(xs: &[u8], i: usize) -> u8 {
164 unsafe { *xs.get_unchecked(i) }
166 fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 {
174 let mut res = String::with_capacity(total);
178 res.as_mut_vec().push_all(&v[..i])
182 // subseqidx is the index of the first byte of the subsequence we're
183 // looking at. It's used to copy a bunch of contiguous good codepoints
184 // at once instead of copying them one by one.
185 let mut subseqidx = i;
189 let byte = unsafe_get(v, i);
192 macro_rules! error { () => ({
195 res.as_mut_vec().push_all(&v[subseqidx..i_]);
198 res.as_mut_vec().push_all(REPLACEMENT);
203 // subseqidx handles this
205 let w = unicode_str::utf8_char_width(byte);
209 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
216 match (byte, safe_get(v, i, total)) {
217 (0xE0 , 0xA0 ... 0xBF) => (),
218 (0xE1 ... 0xEC, 0x80 ... 0xBF) => (),
219 (0xED , 0x80 ... 0x9F) => (),
220 (0xEE ... 0xEF, 0x80 ... 0xBF) => (),
227 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
234 match (byte, safe_get(v, i, total)) {
235 (0xF0 , 0x90 ... 0xBF) => (),
236 (0xF1 ... 0xF3, 0x80 ... 0xBF) => (),
237 (0xF4 , 0x80 ... 0x8F) => (),
244 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
249 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
262 if subseqidx < total {
264 res.as_mut_vec().push_all(&v[subseqidx..total])
270 /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
271 /// if `v` contains any invalid data.
277 /// let mut v = &mut [0xD834, 0xDD1E, 0x006d, 0x0075,
278 /// 0x0073, 0x0069, 0x0063];
279 /// assert_eq!(String::from_utf16(v).unwrap(),
280 /// "𝄞music".to_string());
282 /// // 𝄞mu<invalid>ic
284 /// assert!(String::from_utf16(v).is_err());
286 #[stable(feature = "rust1", since = "1.0.0")]
287 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
288 let mut s = String::with_capacity(v.len());
289 for c in unicode_str::utf16_items(v) {
291 Utf16Item::ScalarValue(c) => s.push(c),
292 Utf16Item::LoneSurrogate(_) => return Err(FromUtf16Error(())),
298 /// Decode a UTF-16 encoded vector `v` into a string, replacing
299 /// invalid data with the replacement character (U+FFFD).
304 /// // 𝄞mus<invalid>ic<invalid>
305 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
306 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
309 /// assert_eq!(String::from_utf16_lossy(v),
310 /// "𝄞mus\u{FFFD}ic\u{FFFD}".to_string());
313 #[stable(feature = "rust1", since = "1.0.0")]
314 pub fn from_utf16_lossy(v: &[u16]) -> String {
315 unicode_str::utf16_items(v).map(|c| c.to_char_lossy()).collect()
318 /// Creates a new `String` from a length, capacity, and pointer.
320 /// This is unsafe because:
322 /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`;
323 /// * We assume that the `Vec` contains valid UTF-8.
325 #[stable(feature = "rust1", since = "1.0.0")]
326 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
328 vec: Vec::from_raw_parts(buf, length, capacity),
332 /// Converts a vector of bytes to a new `String` without checking if
333 /// it contains valid UTF-8. This is unsafe because it assumes that
334 /// the UTF-8-ness of the vector has already been validated.
336 #[stable(feature = "rust1", since = "1.0.0")]
337 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
338 String { vec: bytes }
341 /// Returns the underlying byte buffer, encoded as UTF-8.
346 /// let s = String::from("hello");
347 /// let bytes = s.into_bytes();
348 /// assert_eq!(bytes, [104, 101, 108, 108, 111]);
351 #[stable(feature = "rust1", since = "1.0.0")]
352 pub fn into_bytes(self) -> Vec<u8> {
356 /// Extracts a string slice containing the entire string.
358 #[unstable(feature = "convert",
359 reason = "waiting on RFC revision")]
360 pub fn as_str(&self) -> &str {
364 /// Pushes the given string onto this string buffer.
369 /// let mut s = String::from("foo");
370 /// s.push_str("bar");
371 /// assert_eq!(s, "foobar");
374 #[stable(feature = "rust1", since = "1.0.0")]
375 pub fn push_str(&mut self, string: &str) {
376 self.vec.push_all(string.as_bytes())
379 /// Returns the number of bytes that this string buffer can hold without
385 /// let s = String::with_capacity(10);
386 /// assert!(s.capacity() >= 10);
389 #[stable(feature = "rust1", since = "1.0.0")]
390 pub fn capacity(&self) -> usize {
394 /// Reserves capacity for at least `additional` more bytes to be inserted
395 /// in the given `String`. The collection may reserve more space to avoid
396 /// frequent reallocations.
400 /// Panics if the new capacity overflows `usize`.
405 /// let mut s = String::new();
407 /// assert!(s.capacity() >= 10);
410 #[stable(feature = "rust1", since = "1.0.0")]
411 pub fn reserve(&mut self, additional: usize) {
412 self.vec.reserve(additional)
415 /// Reserves the minimum capacity for exactly `additional` more bytes to be
416 /// inserted in the given `String`. Does nothing if the capacity is already
419 /// Note that the allocator may give the collection more space than it
420 /// requests. Therefore capacity can not be relied upon to be precisely
421 /// minimal. Prefer `reserve` if future insertions are expected.
425 /// Panics if the new capacity overflows `usize`.
430 /// let mut s = String::new();
431 /// s.reserve_exact(10);
432 /// assert!(s.capacity() >= 10);
435 #[stable(feature = "rust1", since = "1.0.0")]
436 pub fn reserve_exact(&mut self, additional: usize) {
437 self.vec.reserve_exact(additional)
440 /// Shrinks the capacity of this string buffer to match its length.
445 /// let mut s = String::from("foo");
447 /// assert!(s.capacity() >= 100);
448 /// s.shrink_to_fit();
449 /// assert_eq!(s.capacity(), 3);
452 #[stable(feature = "rust1", since = "1.0.0")]
453 pub fn shrink_to_fit(&mut self) {
454 self.vec.shrink_to_fit()
457 /// Adds the given character to the end of the string.
462 /// let mut s = String::from("abc");
466 /// assert_eq!(s, "abc123");
469 #[stable(feature = "rust1", since = "1.0.0")]
470 pub fn push(&mut self, ch: char) {
471 if (ch as u32) < 0x80 {
472 self.vec.push(ch as u8);
476 let cur_len = self.len();
477 // This may use up to 4 bytes.
481 // Attempt to not use an intermediate buffer by just pushing bytes
482 // directly onto this string.
483 let slice = slice::from_raw_parts_mut (
484 self.vec.as_mut_ptr().offset(cur_len as isize),
487 let used = ch.encode_utf8(slice).unwrap_or(0);
488 self.vec.set_len(cur_len + used);
492 /// Works with the underlying buffer as a byte slice.
497 /// let s = String::from("hello");
498 /// assert_eq!(s.as_bytes(), [104, 101, 108, 108, 111]);
501 #[stable(feature = "rust1", since = "1.0.0")]
502 pub fn as_bytes(&self) -> &[u8] {
506 /// Shortens a string to the specified length.
510 /// Panics if `new_len` > current length,
511 /// or if `new_len` is not a character boundary.
516 /// let mut s = String::from("hello");
518 /// assert_eq!(s, "he");
521 #[stable(feature = "rust1", since = "1.0.0")]
522 pub fn truncate(&mut self, new_len: usize) {
523 assert!(self.is_char_boundary(new_len));
524 self.vec.truncate(new_len)
527 /// Removes the last character from the string buffer and returns it.
528 /// Returns `None` if this string buffer is empty.
533 /// let mut s = String::from("foo");
534 /// assert_eq!(s.pop(), Some('o'));
535 /// assert_eq!(s.pop(), Some('o'));
536 /// assert_eq!(s.pop(), Some('f'));
537 /// assert_eq!(s.pop(), None);
540 #[stable(feature = "rust1", since = "1.0.0")]
541 pub fn pop(&mut self) -> Option<char> {
542 let len = self.len();
547 let ch = self.char_at_reverse(len);
549 self.vec.set_len(len - ch.len_utf8());
554 /// Removes the character from the string buffer at byte position `idx` and
559 /// This is an O(n) operation as it requires copying every element in the
564 /// If `idx` does not lie on a character boundary, or if it is out of
565 /// bounds, then this function will panic.
570 /// let mut s = String::from("foo");
571 /// assert_eq!(s.remove(0), 'f');
572 /// assert_eq!(s.remove(1), 'o');
573 /// assert_eq!(s.remove(0), 'o');
576 #[stable(feature = "rust1", since = "1.0.0")]
577 pub fn remove(&mut self, idx: usize) -> char {
578 let len = self.len();
581 let ch = self.char_at(idx);
582 let next = idx + ch.len_utf8();
584 ptr::copy(self.vec.as_ptr().offset(next as isize),
585 self.vec.as_mut_ptr().offset(idx as isize),
587 self.vec.set_len(len - (next - idx));
592 /// Inserts a character into the string buffer at byte position `idx`.
596 /// This is an O(n) operation as it requires copying every element in the
601 /// If `idx` does not lie on a character boundary or is out of bounds, then
602 /// this function will panic.
604 #[stable(feature = "rust1", since = "1.0.0")]
605 pub fn insert(&mut self, idx: usize, ch: char) {
606 let len = self.len();
608 assert!(self.is_char_boundary(idx));
610 let mut bits = [0; 4];
611 let amt = ch.encode_utf8(&mut bits).unwrap();
614 ptr::copy(self.vec.as_ptr().offset(idx as isize),
615 self.vec.as_mut_ptr().offset((idx + amt) as isize),
617 ptr::copy(bits.as_ptr(),
618 self.vec.as_mut_ptr().offset(idx as isize),
620 self.vec.set_len(len + amt);
624 /// Views the string buffer as a mutable sequence of bytes.
626 /// This is unsafe because it does not check
627 /// to ensure that the resulting string will be valid UTF-8.
632 /// let mut s = String::from("hello");
634 /// let vec = s.as_mut_vec();
635 /// assert!(vec == &[104, 101, 108, 108, 111]);
638 /// assert_eq!(s, "olleh");
641 #[stable(feature = "rust1", since = "1.0.0")]
642 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
646 /// Returns the number of bytes in this string.
651 /// let a = "foo".to_string();
652 /// assert_eq!(a.len(), 3);
655 #[stable(feature = "rust1", since = "1.0.0")]
656 pub fn len(&self) -> usize { self.vec.len() }
658 /// Returns true if the string contains no bytes
663 /// let mut v = String::new();
664 /// assert!(v.is_empty());
666 /// assert!(!v.is_empty());
669 #[stable(feature = "rust1", since = "1.0.0")]
670 pub fn is_empty(&self) -> bool { self.len() == 0 }
672 /// Truncates the string, returning it to 0 length.
677 /// let mut s = "foo".to_string();
679 /// assert!(s.is_empty());
682 #[stable(feature = "rust1", since = "1.0.0")]
683 pub fn clear(&mut self) {
687 /// Create a draining iterator that removes the specified range in the string
688 /// and yields the removed chars from start to end. The element range is
689 /// removed even if the iterator is not consumed until the end.
693 /// Panics if the starting point or end point are not on character boundaries,
694 /// or if they are out of bounds.
699 /// # #![feature(collections_drain)]
701 /// let mut s = String::from("α is alpha, β is beta");
702 /// let beta_offset = s.find('β').unwrap_or(s.len());
704 /// // Remove the range up until the β from the string
705 /// let t: String = s.drain(..beta_offset).collect();
706 /// assert_eq!(t, "α is alpha, ");
707 /// assert_eq!(s, "β is beta");
709 /// // A full range clears the string
711 /// assert_eq!(s, "");
713 #[unstable(feature = "collections_drain",
714 reason = "recently added, matches RFC")]
715 pub fn drain<R>(&mut self, range: R) -> Drain where R: RangeArgument<usize> {
718 // The String version of Drain does not have the memory safety issues
719 // of the vector version. The data is just plain bytes.
720 // Because the range removal happens in Drop, if the Drain iterator is leaked,
721 // the removal will not happen.
722 let len = self.len();
723 let start = *range.start().unwrap_or(&0);
724 let end = *range.end().unwrap_or(&len);
726 // Take out two simultaneous borrows. The &mut String won't be accessed
727 // until iteration is over, in Drop.
728 let self_ptr = self as *mut _;
729 // slicing does the appropriate bounds checks
730 let chars_iter = self[start..end].chars();
742 /// Consumes this error, returning the bytes that were attempted to make a
744 #[stable(feature = "rust1", since = "1.0.0")]
745 pub fn into_bytes(self) -> Vec<u8> { self.bytes }
747 /// Access the underlying UTF8-error that was the cause of this error.
748 #[stable(feature = "rust1", since = "1.0.0")]
749 pub fn utf8_error(&self) -> Utf8Error { self.error }
752 #[stable(feature = "rust1", since = "1.0.0")]
753 impl fmt::Display for FromUtf8Error {
754 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
755 fmt::Display::fmt(&self.error, f)
759 #[stable(feature = "rust1", since = "1.0.0")]
760 impl fmt::Display for FromUtf16Error {
761 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
762 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
766 #[stable(feature = "rust1", since = "1.0.0")]
767 impl FromIterator<char> for String {
768 fn from_iter<I: IntoIterator<Item=char>>(iter: I) -> String {
769 let mut buf = String::new();
775 #[stable(feature = "rust1", since = "1.0.0")]
776 impl<'a> FromIterator<&'a str> for String {
777 fn from_iter<I: IntoIterator<Item=&'a str>>(iter: I) -> String {
778 let mut buf = String::new();
784 #[stable(feature = "rust1", since = "1.0.0")]
785 impl Extend<char> for String {
786 fn extend<I: IntoIterator<Item=char>>(&mut self, iterable: I) {
787 let iterator = iterable.into_iter();
788 let (lower_bound, _) = iterator.size_hint();
789 self.reserve(lower_bound);
796 #[stable(feature = "rust1", since = "1.0.0")]
797 impl<'a> Extend<&'a str> for String {
798 fn extend<I: IntoIterator<Item=&'a str>>(&mut self, iterable: I) {
799 let iterator = iterable.into_iter();
800 // A guess that at least one byte per iterator element will be needed.
801 let (lower_bound, _) = iterator.size_hint();
802 self.reserve(lower_bound);
809 /// A convenience impl that delegates to the impl for `&str`
810 impl<'a, 'b> Pattern<'a> for &'b String {
811 type Searcher = <&'b str as Pattern<'a>>::Searcher;
813 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
814 self[..].into_searcher(haystack)
818 fn is_contained_in(self, haystack: &'a str) -> bool {
819 self[..].is_contained_in(haystack)
823 fn is_prefix_of(self, haystack: &'a str) -> bool {
824 self[..].is_prefix_of(haystack)
828 #[stable(feature = "rust1", since = "1.0.0")]
829 impl PartialEq for String {
831 fn eq(&self, other: &String) -> bool { PartialEq::eq(&self[..], &other[..]) }
833 fn ne(&self, other: &String) -> bool { PartialEq::ne(&self[..], &other[..]) }
836 macro_rules! impl_eq {
837 ($lhs:ty, $rhs: ty) => {
838 #[stable(feature = "rust1", since = "1.0.0")]
839 impl<'a> PartialEq<$rhs> for $lhs {
841 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
843 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
846 #[stable(feature = "rust1", since = "1.0.0")]
847 impl<'a> PartialEq<$lhs> for $rhs {
849 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
851 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
857 impl_eq! { String, str }
858 impl_eq! { String, &'a str }
859 impl_eq! { Cow<'a, str>, str }
860 impl_eq! { Cow<'a, str>, String }
862 #[stable(feature = "rust1", since = "1.0.0")]
863 impl<'a, 'b> PartialEq<&'b str> for Cow<'a, str> {
865 fn eq(&self, other: &&'b str) -> bool { PartialEq::eq(&self[..], &other[..]) }
867 fn ne(&self, other: &&'b str) -> bool { PartialEq::ne(&self[..], &other[..]) }
870 #[stable(feature = "rust1", since = "1.0.0")]
871 impl<'a, 'b> PartialEq<Cow<'a, str>> for &'b str {
873 fn eq(&self, other: &Cow<'a, str>) -> bool { PartialEq::eq(&self[..], &other[..]) }
875 fn ne(&self, other: &Cow<'a, str>) -> bool { PartialEq::ne(&self[..], &other[..]) }
878 #[stable(feature = "rust1", since = "1.0.0")]
879 impl Default for String {
881 #[stable(feature = "rust1", since = "1.0.0")]
882 fn default() -> String {
887 #[stable(feature = "rust1", since = "1.0.0")]
888 impl fmt::Display for String {
890 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
891 fmt::Display::fmt(&**self, f)
895 #[stable(feature = "rust1", since = "1.0.0")]
896 impl fmt::Debug for String {
898 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
899 fmt::Debug::fmt(&**self, f)
903 #[stable(feature = "rust1", since = "1.0.0")]
904 impl hash::Hash for String {
906 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
907 (**self).hash(hasher)
911 #[stable(feature = "rust1", since = "1.0.0")]
912 impl<'a> Add<&'a str> for String {
913 type Output = String;
916 fn add(mut self, other: &str) -> String {
917 self.push_str(other);
922 #[stable(feature = "rust1", since = "1.0.0")]
923 impl ops::Index<ops::Range<usize>> for String {
927 fn index(&self, index: ops::Range<usize>) -> &str {
931 #[stable(feature = "rust1", since = "1.0.0")]
932 impl ops::Index<ops::RangeTo<usize>> for String {
936 fn index(&self, index: ops::RangeTo<usize>) -> &str {
940 #[stable(feature = "rust1", since = "1.0.0")]
941 impl ops::Index<ops::RangeFrom<usize>> for String {
945 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
949 #[stable(feature = "rust1", since = "1.0.0")]
950 impl ops::Index<ops::RangeFull> for String {
954 fn index(&self, _index: ops::RangeFull) -> &str {
955 unsafe { mem::transmute(&*self.vec) }
959 #[stable(feature = "rust1", since = "1.0.0")]
960 impl ops::Deref for String {
964 fn deref(&self) -> &str {
965 unsafe { mem::transmute(&self.vec[..]) }
969 /// Wrapper type providing a `&String` reference via `Deref`.
970 #[unstable(feature = "collections")]
971 pub struct DerefString<'a> {
975 impl<'a> Deref for DerefString<'a> {
976 type Target = String;
979 fn deref<'b>(&'b self) -> &'b String {
980 unsafe { mem::transmute(&*self.x) }
984 /// Converts a string slice to a wrapper type providing a `&String` reference.
989 /// # #![feature(collections)]
990 /// use std::string::as_string;
992 /// // Let's pretend we have a function that requires `&String`
993 /// fn string_consumer(s: &String) {
994 /// assert_eq!(s, "foo");
997 /// // Provide a `&String` from a `&str` without allocating
998 /// string_consumer(&as_string("foo"));
1000 #[unstable(feature = "collections")]
1001 pub fn as_string<'a>(x: &'a str) -> DerefString<'a> {
1002 DerefString { x: as_vec(x.as_bytes()) }
1005 /// Error returned from `String::from`
1006 #[unstable(feature = "str_parse_error", reason = "may want to be replaced with \
1007 Void if it ever exists")]
1008 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1009 pub struct ParseError(());
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 impl FromStr for String {
1013 type Err = ParseError;
1015 fn from_str(s: &str) -> Result<String, ParseError> {
1020 /// A generic trait for converting a value to a string
1021 #[stable(feature = "rust1", since = "1.0.0")]
1022 pub trait ToString {
1023 /// Converts the value of `self` to an owned string
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 fn to_string(&self) -> String;
1028 #[stable(feature = "rust1", since = "1.0.0")]
1029 impl<T: fmt::Display + ?Sized> ToString for T {
1031 fn to_string(&self) -> String {
1032 use core::fmt::Write;
1033 let mut buf = String::new();
1034 let _ = buf.write_fmt(format_args!("{}", self));
1035 buf.shrink_to_fit();
1040 #[stable(feature = "rust1", since = "1.0.0")]
1041 impl AsRef<str> for String {
1043 fn as_ref(&self) -> &str {
1048 #[stable(feature = "rust1", since = "1.0.0")]
1049 impl AsRef<[u8]> for String {
1051 fn as_ref(&self) -> &[u8] {
1056 #[stable(feature = "rust1", since = "1.0.0")]
1057 impl<'a> From<&'a str> for String {
1060 fn from(s: &'a str) -> String {
1061 String { vec: <[_]>::to_vec(s.as_bytes()) }
1064 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1065 // required for this method definition, is not available. Since we don't
1066 // require this method for testing purposes, I'll just stub it
1067 // NB see the slice::hack module in slice.rs for more information
1070 fn from(_: &str) -> String {
1071 panic!("not available with cfg(test)");
1075 #[stable(feature = "rust1", since = "1.0.0")]
1076 impl<'a> From<&'a str> for Cow<'a, str> {
1078 fn from(s: &'a str) -> Cow<'a, str> {
1083 #[stable(feature = "rust1", since = "1.0.0")]
1084 impl<'a> From<String> for Cow<'a, str> {
1086 fn from(s: String) -> Cow<'a, str> {
1091 #[stable(feature = "rust1", since = "1.0.0")]
1092 impl Into<Vec<u8>> for String {
1093 fn into(self) -> Vec<u8> {
1098 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`")]
1099 impl IntoCow<'static, str> for String {
1101 fn into_cow(self) -> Cow<'static, str> {
1106 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`")]
1107 impl<'a> IntoCow<'a, str> for &'a str {
1109 fn into_cow(self) -> Cow<'a, str> {
1114 #[stable(feature = "rust1", since = "1.0.0")]
1115 impl fmt::Write for String {
1117 fn write_str(&mut self, s: &str) -> fmt::Result {
1123 fn write_char(&mut self, c: char) -> fmt::Result {
1129 /// A draining iterator for `String`.
1130 #[unstable(feature = "collections_drain", reason = "recently added")]
1131 pub struct Drain<'a> {
1132 /// Will be used as &'a mut String in the destructor
1133 string: *mut String,
1134 /// Start of part to remove
1136 /// End of part to remove
1138 /// Current remaining range to remove
1142 unsafe impl<'a> Sync for Drain<'a> {}
1143 unsafe impl<'a> Send for Drain<'a> {}
1145 #[unstable(feature = "collections_drain", reason = "recently added")]
1146 impl<'a> Drop for Drain<'a> {
1147 fn drop(&mut self) {
1149 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
1150 // panic code being inserted again.
1151 let self_vec = (*self.string).as_mut_vec();
1152 if self.start <= self.end && self.end <= self_vec.len() {
1153 self_vec.drain(self.start..self.end);
1159 #[unstable(feature = "collections_drain", reason = "recently added")]
1160 impl<'a> Iterator for Drain<'a> {
1164 fn next(&mut self) -> Option<char> {
1168 fn size_hint(&self) -> (usize, Option<usize>) {
1169 self.iter.size_hint()
1173 #[unstable(feature = "collections_drain", reason = "recently added")]
1174 impl<'a> DoubleEndedIterator for Drain<'a> {
1176 fn next_back(&mut self) -> Option<char> {
1177 self.iter.next_back()