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, core)]
92 /// let s = String::from_str("hello");
93 /// assert_eq!(&s[..], "hello");
96 #[unstable(feature = "collections",
97 reason = "needs investigation to see if to_string() can match perf")]
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 /// # #![feature(core)]
125 /// use std::str::Utf8Error;
127 /// let hello_vec = vec![104, 101, 108, 108, 111];
128 /// let s = String::from_utf8(hello_vec).unwrap();
129 /// assert_eq!(s, "hello");
131 /// let invalid_vec = vec![240, 144, 128];
132 /// let s = String::from_utf8(invalid_vec).err().unwrap();
133 /// let err = s.utf8_error();
134 /// assert_eq!(s.into_bytes(), [240, 144, 128]);
137 #[stable(feature = "rust1", since = "1.0.0")]
138 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
139 match str::from_utf8(&vec) {
140 Ok(..) => Ok(String { vec: vec }),
141 Err(e) => Err(FromUtf8Error { bytes: vec, error: e })
145 /// Converts a vector of bytes to a new UTF-8 string.
146 /// Any invalid UTF-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
151 /// let input = b"Hello \xF0\x90\x80World";
152 /// let output = String::from_utf8_lossy(input);
153 /// assert_eq!(output, "Hello \u{FFFD}World");
155 #[stable(feature = "rust1", since = "1.0.0")]
156 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
158 match str::from_utf8(v) {
159 Ok(s) => return Cow::Borrowed(s),
160 Err(e) => i = e.valid_up_to(),
163 const TAG_CONT_U8: u8 = 128;
164 const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
166 fn unsafe_get(xs: &[u8], i: usize) -> u8 {
167 unsafe { *xs.get_unchecked(i) }
169 fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 {
177 let mut res = String::with_capacity(total);
181 res.as_mut_vec().push_all(&v[..i])
185 // subseqidx is the index of the first byte of the subsequence we're
186 // looking at. It's used to copy a bunch of contiguous good codepoints
187 // at once instead of copying them one by one.
188 let mut subseqidx = i;
192 let byte = unsafe_get(v, i);
195 macro_rules! error { () => ({
198 res.as_mut_vec().push_all(&v[subseqidx..i_]);
201 res.as_mut_vec().push_all(REPLACEMENT);
206 // subseqidx handles this
208 let w = unicode_str::utf8_char_width(byte);
212 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
219 match (byte, safe_get(v, i, total)) {
220 (0xE0 , 0xA0 ... 0xBF) => (),
221 (0xE1 ... 0xEC, 0x80 ... 0xBF) => (),
222 (0xED , 0x80 ... 0x9F) => (),
223 (0xEE ... 0xEF, 0x80 ... 0xBF) => (),
230 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
237 match (byte, safe_get(v, i, total)) {
238 (0xF0 , 0x90 ... 0xBF) => (),
239 (0xF1 ... 0xF3, 0x80 ... 0xBF) => (),
240 (0xF4 , 0x80 ... 0x8F) => (),
247 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
252 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
265 if subseqidx < total {
267 res.as_mut_vec().push_all(&v[subseqidx..total])
273 /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
274 /// if `v` contains any invalid data.
280 /// let mut v = &mut [0xD834, 0xDD1E, 0x006d, 0x0075,
281 /// 0x0073, 0x0069, 0x0063];
282 /// assert_eq!(String::from_utf16(v).unwrap(),
283 /// "𝄞music".to_string());
285 /// // 𝄞mu<invalid>ic
287 /// assert!(String::from_utf16(v).is_err());
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
291 let mut s = String::with_capacity(v.len());
292 for c in unicode_str::utf16_items(v) {
294 Utf16Item::ScalarValue(c) => s.push(c),
295 Utf16Item::LoneSurrogate(_) => return Err(FromUtf16Error(())),
301 /// Decode a UTF-16 encoded vector `v` into a string, replacing
302 /// invalid data with the replacement character (U+FFFD).
307 /// // 𝄞mus<invalid>ic<invalid>
308 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
309 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
312 /// assert_eq!(String::from_utf16_lossy(v),
313 /// "𝄞mus\u{FFFD}ic\u{FFFD}".to_string());
316 #[stable(feature = "rust1", since = "1.0.0")]
317 pub fn from_utf16_lossy(v: &[u16]) -> String {
318 unicode_str::utf16_items(v).map(|c| c.to_char_lossy()).collect()
321 /// Creates a new `String` from a length, capacity, and pointer.
323 /// This is unsafe because:
325 /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`;
326 /// * We assume that the `Vec` contains valid UTF-8.
328 #[stable(feature = "rust1", since = "1.0.0")]
329 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
331 vec: Vec::from_raw_parts(buf, length, capacity),
335 /// Converts a vector of bytes to a new `String` without checking if
336 /// it contains valid UTF-8. This is unsafe because it assumes that
337 /// the UTF-8-ness of the vector has already been validated.
339 #[stable(feature = "rust1", since = "1.0.0")]
340 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
341 String { vec: bytes }
344 /// Returns the underlying byte buffer, encoded as UTF-8.
349 /// # #![feature(collections)]
350 /// let s = String::from_str("hello");
351 /// let bytes = s.into_bytes();
352 /// assert_eq!(bytes, [104, 101, 108, 108, 111]);
355 #[stable(feature = "rust1", since = "1.0.0")]
356 pub fn into_bytes(self) -> Vec<u8> {
360 /// Extracts a string slice containing the entire string.
362 #[unstable(feature = "convert",
363 reason = "waiting on RFC revision")]
364 pub fn as_str(&self) -> &str {
368 /// Pushes the given string onto this string buffer.
373 /// # #![feature(collections)]
374 /// let mut s = String::from_str("foo");
375 /// s.push_str("bar");
376 /// assert_eq!(s, "foobar");
379 #[stable(feature = "rust1", since = "1.0.0")]
380 pub fn push_str(&mut self, string: &str) {
381 self.vec.push_all(string.as_bytes())
384 /// Returns the number of bytes that this string buffer can hold without
390 /// let s = String::with_capacity(10);
391 /// assert!(s.capacity() >= 10);
394 #[stable(feature = "rust1", since = "1.0.0")]
395 pub fn capacity(&self) -> usize {
399 /// Reserves capacity for at least `additional` more bytes to be inserted
400 /// in the given `String`. The collection may reserve more space to avoid
401 /// frequent reallocations.
405 /// Panics if the new capacity overflows `usize`.
410 /// let mut s = String::new();
412 /// assert!(s.capacity() >= 10);
415 #[stable(feature = "rust1", since = "1.0.0")]
416 pub fn reserve(&mut self, additional: usize) {
417 self.vec.reserve(additional)
420 /// Reserves the minimum capacity for exactly `additional` more bytes to be
421 /// inserted in the given `String`. Does nothing if the capacity is already
424 /// Note that the allocator may give the collection more space than it
425 /// requests. Therefore capacity can not be relied upon to be precisely
426 /// minimal. Prefer `reserve` if future insertions are expected.
430 /// Panics if the new capacity overflows `usize`.
435 /// let mut s = String::new();
436 /// s.reserve_exact(10);
437 /// assert!(s.capacity() >= 10);
440 #[stable(feature = "rust1", since = "1.0.0")]
441 pub fn reserve_exact(&mut self, additional: usize) {
442 self.vec.reserve_exact(additional)
445 /// Shrinks the capacity of this string buffer to match its length.
450 /// # #![feature(collections)]
451 /// let mut s = String::from_str("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 /// # #![feature(collections)]
469 /// let mut s = String::from_str("abc");
473 /// assert_eq!(s, "abc123");
476 #[stable(feature = "rust1", since = "1.0.0")]
477 pub fn push(&mut self, ch: char) {
478 if (ch as u32) < 0x80 {
479 self.vec.push(ch as u8);
483 let cur_len = self.len();
484 // This may use up to 4 bytes.
488 // Attempt to not use an intermediate buffer by just pushing bytes
489 // directly onto this string.
490 let slice = slice::from_raw_parts_mut (
491 self.vec.as_mut_ptr().offset(cur_len as isize),
494 let used = ch.encode_utf8(slice).unwrap_or(0);
495 self.vec.set_len(cur_len + used);
499 /// Works with the underlying buffer as a byte slice.
504 /// # #![feature(collections)]
505 /// let s = String::from_str("hello");
506 /// let b: &[_] = &[104, 101, 108, 108, 111];
507 /// assert_eq!(s.as_bytes(), b);
510 #[stable(feature = "rust1", since = "1.0.0")]
511 pub fn as_bytes(&self) -> &[u8] {
515 /// Shortens a string to the specified length.
519 /// Panics if `new_len` > current length,
520 /// or if `new_len` is not a character boundary.
525 /// # #![feature(collections)]
526 /// let mut s = String::from_str("hello");
528 /// assert_eq!(s, "he");
531 #[stable(feature = "rust1", since = "1.0.0")]
532 pub fn truncate(&mut self, new_len: usize) {
533 assert!(self.is_char_boundary(new_len));
534 self.vec.truncate(new_len)
537 /// Removes the last character from the string buffer and returns it.
538 /// Returns `None` if this string buffer is empty.
543 /// # #![feature(collections)]
544 /// let mut s = String::from_str("foo");
545 /// assert_eq!(s.pop(), Some('o'));
546 /// assert_eq!(s.pop(), Some('o'));
547 /// assert_eq!(s.pop(), Some('f'));
548 /// assert_eq!(s.pop(), None);
551 #[stable(feature = "rust1", since = "1.0.0")]
552 pub fn pop(&mut self) -> Option<char> {
553 let len = self.len();
558 let ch = self.char_at_reverse(len);
560 self.vec.set_len(len - ch.len_utf8());
565 /// Removes the character from the string buffer at byte position `idx` and
570 /// This is an O(n) operation as it requires copying every element in the
575 /// If `idx` does not lie on a character boundary, or if it is out of
576 /// bounds, then this function will panic.
581 /// # #![feature(collections)]
582 /// let mut s = String::from_str("foo");
583 /// assert_eq!(s.remove(0), 'f');
584 /// assert_eq!(s.remove(1), 'o');
585 /// assert_eq!(s.remove(0), 'o');
588 #[stable(feature = "rust1", since = "1.0.0")]
589 pub fn remove(&mut self, idx: usize) -> char {
590 let len = self.len();
593 let ch = self.char_at(idx);
594 let next = idx + ch.len_utf8();
596 ptr::copy(self.vec.as_ptr().offset(next as isize),
597 self.vec.as_mut_ptr().offset(idx as isize),
599 self.vec.set_len(len - (next - idx));
604 /// Inserts a character into the string buffer at byte position `idx`.
608 /// This is an O(n) operation as it requires copying every element in the
613 /// If `idx` does not lie on a character boundary or is out of bounds, then
614 /// this function will panic.
616 #[stable(feature = "rust1", since = "1.0.0")]
617 pub fn insert(&mut self, idx: usize, ch: char) {
618 let len = self.len();
620 assert!(self.is_char_boundary(idx));
622 let mut bits = [0; 4];
623 let amt = ch.encode_utf8(&mut bits).unwrap();
626 ptr::copy(self.vec.as_ptr().offset(idx as isize),
627 self.vec.as_mut_ptr().offset((idx + amt) as isize),
629 ptr::copy(bits.as_ptr(),
630 self.vec.as_mut_ptr().offset(idx as isize),
632 self.vec.set_len(len + amt);
636 /// Views the string buffer as a mutable sequence of bytes.
638 /// This is unsafe because it does not check
639 /// to ensure that the resulting string will be valid UTF-8.
644 /// # #![feature(collections)]
645 /// let mut s = String::from_str("hello");
647 /// let vec = s.as_mut_vec();
648 /// assert!(vec == &[104, 101, 108, 108, 111]);
651 /// assert_eq!(s, "olleh");
654 #[stable(feature = "rust1", since = "1.0.0")]
655 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
659 /// Returns the number of bytes in this string.
664 /// let a = "foo".to_string();
665 /// assert_eq!(a.len(), 3);
668 #[stable(feature = "rust1", since = "1.0.0")]
669 pub fn len(&self) -> usize { self.vec.len() }
671 /// Returns true if the string contains no bytes
676 /// let mut v = String::new();
677 /// assert!(v.is_empty());
679 /// assert!(!v.is_empty());
682 #[stable(feature = "rust1", since = "1.0.0")]
683 pub fn is_empty(&self) -> bool { self.len() == 0 }
685 /// Truncates the string, returning it to 0 length.
690 /// let mut s = "foo".to_string();
692 /// assert!(s.is_empty());
695 #[stable(feature = "rust1", since = "1.0.0")]
696 pub fn clear(&mut self) {
700 /// Create a draining iterator that removes the specified range in the string
701 /// and yields the removed chars from start to end. The element range is
702 /// removed even if the iterator is not consumed until the end.
706 /// Panics if the starting point or end point are not on character boundaries,
707 /// or if they are out of bounds.
712 /// # #![feature(collections_drain)]
714 /// let mut s = String::from("α is alpha, β is beta");
715 /// let beta_offset = s.find('β').unwrap_or(s.len());
717 /// // Remove the range up until the β from the string
718 /// let t: String = s.drain(..beta_offset).collect();
719 /// assert_eq!(t, "α is alpha, ");
720 /// assert_eq!(s, "β is beta");
722 /// // A full range clears the string
724 /// assert_eq!(s, "");
726 #[unstable(feature = "collections_drain",
727 reason = "recently added, matches RFC")]
728 pub fn drain<R>(&mut self, range: R) -> Drain where R: RangeArgument<usize> {
731 // The String version of Drain does not have the memory safety issues
732 // of the vector version. The data is just plain bytes.
733 // Because the range removal happens in Drop, if the Drain iterator is leaked,
734 // the removal will not happen.
735 let len = self.len();
736 let start = *range.start().unwrap_or(&0);
737 let end = *range.end().unwrap_or(&len);
739 // Take out two simultaneous borrows. The &mut String won't be accessed
740 // until iteration is over, in Drop.
741 let self_ptr = self as *mut _;
742 // slicing does the appropriate bounds checks
743 let chars_iter = self[start..end].chars();
755 /// Consumes this error, returning the bytes that were attempted to make a
757 #[stable(feature = "rust1", since = "1.0.0")]
758 pub fn into_bytes(self) -> Vec<u8> { self.bytes }
760 /// Access the underlying UTF8-error that was the cause of this error.
761 #[stable(feature = "rust1", since = "1.0.0")]
762 pub fn utf8_error(&self) -> Utf8Error { self.error }
765 #[stable(feature = "rust1", since = "1.0.0")]
766 impl fmt::Display for FromUtf8Error {
767 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
768 fmt::Display::fmt(&self.error, f)
772 #[stable(feature = "rust1", since = "1.0.0")]
773 impl fmt::Display for FromUtf16Error {
774 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
775 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
779 #[stable(feature = "rust1", since = "1.0.0")]
780 impl FromIterator<char> for String {
781 fn from_iter<I: IntoIterator<Item=char>>(iter: I) -> String {
782 let mut buf = String::new();
788 #[stable(feature = "rust1", since = "1.0.0")]
789 impl<'a> FromIterator<&'a str> for String {
790 fn from_iter<I: IntoIterator<Item=&'a str>>(iter: I) -> String {
791 let mut buf = String::new();
797 #[stable(feature = "rust1", since = "1.0.0")]
798 impl Extend<char> for String {
799 fn extend<I: IntoIterator<Item=char>>(&mut self, iterable: I) {
800 let iterator = iterable.into_iter();
801 let (lower_bound, _) = iterator.size_hint();
802 self.reserve(lower_bound);
809 #[stable(feature = "rust1", since = "1.0.0")]
810 impl<'a> Extend<&'a str> for String {
811 fn extend<I: IntoIterator<Item=&'a str>>(&mut self, iterable: I) {
812 let iterator = iterable.into_iter();
813 // A guess that at least one byte per iterator element will be needed.
814 let (lower_bound, _) = iterator.size_hint();
815 self.reserve(lower_bound);
822 /// A convenience impl that delegates to the impl for `&str`
823 impl<'a, 'b> Pattern<'a> for &'b String {
824 type Searcher = <&'b str as Pattern<'a>>::Searcher;
826 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
827 self[..].into_searcher(haystack)
831 fn is_contained_in(self, haystack: &'a str) -> bool {
832 self[..].is_contained_in(haystack)
836 fn is_prefix_of(self, haystack: &'a str) -> bool {
837 self[..].is_prefix_of(haystack)
841 #[stable(feature = "rust1", since = "1.0.0")]
842 impl PartialEq for String {
844 fn eq(&self, other: &String) -> bool { PartialEq::eq(&self[..], &other[..]) }
846 fn ne(&self, other: &String) -> bool { PartialEq::ne(&self[..], &other[..]) }
849 macro_rules! impl_eq {
850 ($lhs:ty, $rhs: ty) => {
851 #[stable(feature = "rust1", since = "1.0.0")]
852 impl<'a> PartialEq<$rhs> for $lhs {
854 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
856 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
859 #[stable(feature = "rust1", since = "1.0.0")]
860 impl<'a> PartialEq<$lhs> for $rhs {
862 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
864 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
870 impl_eq! { String, str }
871 impl_eq! { String, &'a str }
872 impl_eq! { Cow<'a, str>, str }
873 impl_eq! { Cow<'a, str>, String }
875 #[stable(feature = "rust1", since = "1.0.0")]
876 impl<'a, 'b> PartialEq<&'b str> for Cow<'a, str> {
878 fn eq(&self, other: &&'b str) -> bool { PartialEq::eq(&self[..], &other[..]) }
880 fn ne(&self, other: &&'b str) -> bool { PartialEq::ne(&self[..], &other[..]) }
883 #[stable(feature = "rust1", since = "1.0.0")]
884 impl<'a, 'b> PartialEq<Cow<'a, str>> for &'b str {
886 fn eq(&self, other: &Cow<'a, str>) -> bool { PartialEq::eq(&self[..], &other[..]) }
888 fn ne(&self, other: &Cow<'a, str>) -> bool { PartialEq::ne(&self[..], &other[..]) }
891 #[stable(feature = "rust1", since = "1.0.0")]
892 impl Default for String {
894 #[stable(feature = "rust1", since = "1.0.0")]
895 fn default() -> String {
900 #[stable(feature = "rust1", since = "1.0.0")]
901 impl fmt::Display for String {
903 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
904 fmt::Display::fmt(&**self, f)
908 #[stable(feature = "rust1", since = "1.0.0")]
909 impl fmt::Debug for String {
911 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
912 fmt::Debug::fmt(&**self, f)
916 #[stable(feature = "rust1", since = "1.0.0")]
917 impl hash::Hash for String {
919 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
920 (**self).hash(hasher)
924 #[stable(feature = "rust1", since = "1.0.0")]
925 impl<'a> Add<&'a str> for String {
926 type Output = String;
929 fn add(mut self, other: &str) -> String {
930 self.push_str(other);
935 #[stable(feature = "rust1", since = "1.0.0")]
936 impl ops::Index<ops::Range<usize>> for String {
940 fn index(&self, index: ops::Range<usize>) -> &str {
944 #[stable(feature = "rust1", since = "1.0.0")]
945 impl ops::Index<ops::RangeTo<usize>> for String {
949 fn index(&self, index: ops::RangeTo<usize>) -> &str {
953 #[stable(feature = "rust1", since = "1.0.0")]
954 impl ops::Index<ops::RangeFrom<usize>> for String {
958 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
962 #[stable(feature = "rust1", since = "1.0.0")]
963 impl ops::Index<ops::RangeFull> for String {
967 fn index(&self, _index: ops::RangeFull) -> &str {
968 unsafe { mem::transmute(&*self.vec) }
972 #[stable(feature = "rust1", since = "1.0.0")]
973 impl ops::Deref for String {
977 fn deref(&self) -> &str {
978 unsafe { mem::transmute(&self.vec[..]) }
982 /// Wrapper type providing a `&String` reference via `Deref`.
983 #[unstable(feature = "collections")]
984 pub struct DerefString<'a> {
988 impl<'a> Deref for DerefString<'a> {
989 type Target = String;
992 fn deref<'b>(&'b self) -> &'b String {
993 unsafe { mem::transmute(&*self.x) }
997 /// Converts a string slice to a wrapper type providing a `&String` reference.
1002 /// # #![feature(collections)]
1003 /// use std::string::as_string;
1005 /// // Let's pretend we have a function that requires `&String`
1006 /// fn string_consumer(s: &String) {
1007 /// assert_eq!(s, "foo");
1010 /// // Provide a `&String` from a `&str` without allocating
1011 /// string_consumer(&as_string("foo"));
1013 #[unstable(feature = "collections")]
1014 pub fn as_string<'a>(x: &'a str) -> DerefString<'a> {
1015 DerefString { x: as_vec(x.as_bytes()) }
1018 /// Error returned from `String::from_str`
1019 #[unstable(feature = "str_parse_error", reason = "may want to be replaced with \
1020 Void if it ever exists")]
1021 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1022 pub struct ParseError(());
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 impl FromStr for String {
1026 type Err = ParseError;
1028 fn from_str(s: &str) -> Result<String, ParseError> {
1029 Ok(String::from_str(s))
1033 /// A generic trait for converting a value to a string
1034 #[stable(feature = "rust1", since = "1.0.0")]
1035 pub trait ToString {
1036 /// Converts the value of `self` to an owned string
1037 #[stable(feature = "rust1", since = "1.0.0")]
1038 fn to_string(&self) -> String;
1041 #[stable(feature = "rust1", since = "1.0.0")]
1042 impl<T: fmt::Display + ?Sized> ToString for T {
1044 fn to_string(&self) -> String {
1045 use core::fmt::Write;
1046 let mut buf = String::new();
1047 let _ = buf.write_fmt(format_args!("{}", self));
1048 buf.shrink_to_fit();
1053 #[stable(feature = "rust1", since = "1.0.0")]
1054 impl AsRef<str> for String {
1056 fn as_ref(&self) -> &str {
1061 #[stable(feature = "rust1", since = "1.0.0")]
1062 impl AsRef<[u8]> for String {
1064 fn as_ref(&self) -> &[u8] {
1069 #[stable(feature = "rust1", since = "1.0.0")]
1070 impl<'a> From<&'a str> for String {
1073 fn from(s: &'a str) -> String {
1074 String { vec: <[_]>::to_vec(s.as_bytes()) }
1077 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1078 // required for this method definition, is not available. Since we don't
1079 // require this method for testing purposes, I'll just stub it
1080 // NB see the slice::hack module in slice.rs for more information
1083 fn from(_: &str) -> String {
1084 panic!("not available with cfg(test)");
1088 #[stable(feature = "rust1", since = "1.0.0")]
1089 impl<'a> From<&'a str> for Cow<'a, str> {
1091 fn from(s: &'a str) -> Cow<'a, str> {
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 impl<'a> From<String> for Cow<'a, str> {
1099 fn from(s: String) -> Cow<'a, str> {
1104 #[stable(feature = "rust1", since = "1.0.0")]
1105 impl Into<Vec<u8>> for String {
1106 fn into(self) -> Vec<u8> {
1111 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`")]
1112 impl IntoCow<'static, str> for String {
1114 fn into_cow(self) -> Cow<'static, str> {
1119 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`")]
1120 impl<'a> IntoCow<'a, str> for &'a str {
1122 fn into_cow(self) -> Cow<'a, str> {
1127 #[stable(feature = "rust1", since = "1.0.0")]
1128 impl fmt::Write for String {
1130 fn write_str(&mut self, s: &str) -> fmt::Result {
1136 fn write_char(&mut self, c: char) -> fmt::Result {
1142 /// A draining iterator for `String`.
1143 #[unstable(feature = "collections_drain", reason = "recently added")]
1144 pub struct Drain<'a> {
1145 /// Will be used as &'a mut String in the destructor
1146 string: *mut String,
1147 /// Start of part to remove
1149 /// End of part to remove
1151 /// Current remaining range to remove
1155 unsafe impl<'a> Sync for Drain<'a> {}
1156 unsafe impl<'a> Send for Drain<'a> {}
1158 #[unstable(feature = "collections_drain", reason = "recently added")]
1159 impl<'a> Drop for Drain<'a> {
1160 fn drop(&mut self) {
1162 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
1163 // panic code being inserted again.
1164 let self_vec = (*self.string).as_mut_vec();
1165 if self.start <= self.end && self.end <= self_vec.len() {
1166 self_vec.drain(self.start..self.end);
1172 #[unstable(feature = "collections_drain", reason = "recently added")]
1173 impl<'a> Iterator for Drain<'a> {
1177 fn next(&mut self) -> Option<char> {
1181 fn size_hint(&self) -> (usize, Option<usize>) {
1182 self.iter.size_hint()
1186 #[unstable(feature = "collections_drain", reason = "recently added")]
1187 impl<'a> DoubleEndedIterator for Drain<'a> {
1189 fn next_back(&mut self) -> Option<char> {
1190 self.iter.next_back()