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 match ch
.len_utf8() {
472 1 => self.vec
.push(ch
as u8),
474 let cur_len
= self.len();
475 // This may use up to 4 bytes.
476 self.vec
.reserve(ch_len
);
479 // Attempt to not use an intermediate buffer by just pushing bytes
480 // directly onto this string.
481 let slice
= slice
::from_raw_parts_mut (
482 self.vec
.as_mut_ptr().offset(cur_len
as isize),
485 let used
= ch
.encode_utf8(slice
).unwrap_or(0);
486 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(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 = "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 = "extend_ref", since = "1.2.0")]
797 impl<'a
> Extend
<&'a
char> for String
{
798 fn extend
<I
: IntoIterator
<Item
=&'a
char>>(&mut self, iter
: I
) {
799 self.extend(iter
.into_iter().cloned());
803 #[stable(feature = "rust1", since = "1.0.0")]
804 impl<'a
> Extend
<&'a
str> for String
{
805 fn extend
<I
: IntoIterator
<Item
=&'a
str>>(&mut self, iterable
: I
) {
806 let iterator
= iterable
.into_iter();
807 // A guess that at least one byte per iterator element will be needed.
808 let (lower_bound
, _
) = iterator
.size_hint();
809 self.reserve(lower_bound
);
816 /// A convenience impl that delegates to the impl for `&str`
817 impl<'a
, 'b
> Pattern
<'a
> for &'b String
{
818 type Searcher
= <&'b
str as Pattern
<'a
>>::Searcher
;
820 fn into_searcher(self, haystack
: &'a
str) -> <&'b
str as Pattern
<'a
>>::Searcher
{
821 self[..].into_searcher(haystack
)
825 fn is_contained_in(self, haystack
: &'a
str) -> bool
{
826 self[..].is_contained_in(haystack
)
830 fn is_prefix_of(self, haystack
: &'a
str) -> bool
{
831 self[..].is_prefix_of(haystack
)
835 #[stable(feature = "rust1", since = "1.0.0")]
836 impl PartialEq
for String
{
838 fn eq(&self, other
: &String
) -> bool { PartialEq::eq(&self[..], &other[..]) }
840 fn ne(&self, other
: &String
) -> bool { PartialEq::ne(&self[..], &other[..]) }
843 macro_rules
! impl_eq
{
844 ($lhs
:ty
, $rhs
: ty
) => {
845 #[stable(feature = "rust1", since = "1.0.0")]
846 impl<'a
> PartialEq
<$rhs
> for $lhs
{
848 fn eq(&self, other
: &$rhs
) -> bool { PartialEq::eq(&self[..], &other[..]) }
850 fn ne(&self, other
: &$rhs
) -> bool { PartialEq::ne(&self[..], &other[..]) }
853 #[stable(feature = "rust1", since = "1.0.0")]
854 impl<'a
> PartialEq
<$lhs
> for $rhs
{
856 fn eq(&self, other
: &$lhs
) -> bool { PartialEq::eq(&self[..], &other[..]) }
858 fn ne(&self, other
: &$lhs
) -> bool { PartialEq::ne(&self[..], &other[..]) }
864 impl_eq
! { String, str }
865 impl_eq
! { String, &'a str }
866 impl_eq
! { Cow<'a, str>, str }
867 impl_eq
! { Cow<'a, str>, String }
869 #[stable(feature = "rust1", since = "1.0.0")]
870 impl<'a
, 'b
> PartialEq
<&'b
str> for Cow
<'a
, str> {
872 fn eq(&self, other
: &&'b
str) -> bool { PartialEq::eq(&self[..], &other[..]) }
874 fn ne(&self, other
: &&'b
str) -> bool { PartialEq::ne(&self[..], &other[..]) }
877 #[stable(feature = "rust1", since = "1.0.0")]
878 impl<'a
, 'b
> PartialEq
<Cow
<'a
, str>> for &'b
str {
880 fn eq(&self, other
: &Cow
<'a
, str>) -> bool { PartialEq::eq(&self[..], &other[..]) }
882 fn ne(&self, other
: &Cow
<'a
, str>) -> bool { PartialEq::ne(&self[..], &other[..]) }
885 #[stable(feature = "rust1", since = "1.0.0")]
886 impl Default
for String
{
888 #[stable(feature = "rust1", since = "1.0.0")]
889 fn default() -> String
{
894 #[stable(feature = "rust1", since = "1.0.0")]
895 impl fmt
::Display
for String
{
897 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
898 fmt
::Display
::fmt(&**self, f
)
902 #[stable(feature = "rust1", since = "1.0.0")]
903 impl fmt
::Debug
for String
{
905 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
906 fmt
::Debug
::fmt(&**self, f
)
910 #[stable(feature = "rust1", since = "1.0.0")]
911 impl hash
::Hash
for String
{
913 fn hash
<H
: hash
::Hasher
>(&self, hasher
: &mut H
) {
914 (**self).hash(hasher
)
918 #[stable(feature = "rust1", since = "1.0.0")]
919 impl<'a
> Add
<&'a
str> for String
{
920 type Output
= String
;
923 fn add(mut self, other
: &str) -> String
{
924 self.push_str(other
);
929 #[stable(feature = "rust1", since = "1.0.0")]
930 impl ops
::Index
<ops
::Range
<usize>> for String
{
934 fn index(&self, index
: ops
::Range
<usize>) -> &str {
938 #[stable(feature = "rust1", since = "1.0.0")]
939 impl ops
::Index
<ops
::RangeTo
<usize>> for String
{
943 fn index(&self, index
: ops
::RangeTo
<usize>) -> &str {
947 #[stable(feature = "rust1", since = "1.0.0")]
948 impl ops
::Index
<ops
::RangeFrom
<usize>> for String
{
952 fn index(&self, index
: ops
::RangeFrom
<usize>) -> &str {
956 #[stable(feature = "rust1", since = "1.0.0")]
957 impl ops
::Index
<ops
::RangeFull
> for String
{
961 fn index(&self, _index
: ops
::RangeFull
) -> &str {
962 unsafe { mem::transmute(&*self.vec) }
966 #[stable(feature = "rust1", since = "1.0.0")]
967 impl ops
::Deref
for String
{
971 fn deref(&self) -> &str {
972 unsafe { mem::transmute(&self.vec[..]) }
976 /// Wrapper type providing a `&String` reference via `Deref`.
977 #[unstable(feature = "collections")]
978 #[deprecated(since = "1.2.0",
979 reason
= "replaced with deref coercions or Borrow")]
981 pub struct DerefString
<'a
> {
986 impl<'a
> Deref
for DerefString
<'a
> {
987 type Target
= String
;
990 fn deref
<'b
>(&'b
self) -> &'b String
{
991 unsafe { mem::transmute(&*self.x) }
995 /// Converts a string slice to a wrapper type providing a `&String` reference.
1000 /// # #![feature(collections)]
1001 /// use std::string::as_string;
1003 /// // Let's pretend we have a function that requires `&String`
1004 /// fn string_consumer(s: &String) {
1005 /// assert_eq!(s, "foo");
1008 /// // Provide a `&String` from a `&str` without allocating
1009 /// string_consumer(&as_string("foo"));
1011 #[unstable(feature = "collections")]
1012 #[deprecated(since = "1.2.0",
1013 reason
= "replaced with deref coercions or Borrow")]
1014 #[allow(deprecated)]
1015 pub fn as_string
<'a
>(x
: &'a
str) -> DerefString
<'a
> {
1016 DerefString { x: as_vec(x.as_bytes()) }
1019 /// Error returned from `String::from`
1020 #[unstable(feature = "str_parse_error", reason = "may want to be replaced with \
1021 Void if it ever exists")]
1022 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1023 pub struct ParseError(());
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 impl FromStr
for String
{
1027 type Err
= ParseError
;
1029 fn from_str(s
: &str) -> Result
<String
, ParseError
> {
1034 /// A generic trait for converting a value to a string
1035 #[stable(feature = "rust1", since = "1.0.0")]
1036 pub trait ToString
{
1037 /// Converts the value of `self` to an owned string
1038 #[stable(feature = "rust1", since = "1.0.0")]
1039 fn to_string(&self) -> String
;
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 impl<T
: fmt
::Display
+ ?Sized
> ToString
for T
{
1045 fn to_string(&self) -> String
{
1046 use core
::fmt
::Write
;
1047 let mut buf
= String
::new();
1048 let _
= buf
.write_fmt(format_args
!("{}", self));
1049 buf
.shrink_to_fit();
1054 #[stable(feature = "rust1", since = "1.0.0")]
1055 impl AsRef
<str> for String
{
1057 fn as_ref(&self) -> &str {
1062 #[stable(feature = "rust1", since = "1.0.0")]
1063 impl AsRef
<[u8]> for String
{
1065 fn as_ref(&self) -> &[u8] {
1070 #[stable(feature = "rust1", since = "1.0.0")]
1071 impl<'a
> From
<&'a
str> for String
{
1074 fn from(s
: &'a
str) -> String
{
1075 String { vec: <[_]>::to_vec(s.as_bytes()) }
1078 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1079 // required for this method definition, is not available. Since we don't
1080 // require this method for testing purposes, I'll just stub it
1081 // NB see the slice::hack module in slice.rs for more information
1084 fn from(_
: &str) -> String
{
1085 panic
!("not available with cfg(test)");
1089 #[stable(feature = "rust1", since = "1.0.0")]
1090 impl<'a
> From
<&'a
str> for Cow
<'a
, str> {
1092 fn from(s
: &'a
str) -> Cow
<'a
, str> {
1097 #[stable(feature = "rust1", since = "1.0.0")]
1098 impl<'a
> From
<String
> for Cow
<'a
, str> {
1100 fn from(s
: String
) -> Cow
<'a
, str> {
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 impl Into
<Vec
<u8>> for String
{
1107 fn into(self) -> Vec
<u8> {
1112 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`")]
1113 impl IntoCow
<'
static, str> for String
{
1115 fn into_cow(self) -> Cow
<'
static, str> {
1120 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`")]
1121 impl<'a
> IntoCow
<'a
, str> for &'a
str {
1123 fn into_cow(self) -> Cow
<'a
, str> {
1128 #[stable(feature = "rust1", since = "1.0.0")]
1129 impl fmt
::Write
for String
{
1131 fn write_str(&mut self, s
: &str) -> fmt
::Result
{
1137 fn write_char(&mut self, c
: char) -> fmt
::Result
{
1143 /// A draining iterator for `String`.
1144 #[unstable(feature = "drain", reason = "recently added")]
1145 pub struct Drain
<'a
> {
1146 /// Will be used as &'a mut String in the destructor
1147 string
: *mut String
,
1148 /// Start of part to remove
1150 /// End of part to remove
1152 /// Current remaining range to remove
1156 unsafe impl<'a
> Sync
for Drain
<'a
> {}
1157 unsafe impl<'a
> Send
for Drain
<'a
> {}
1159 #[unstable(feature = "drain", reason = "recently added")]
1160 impl<'a
> Drop
for Drain
<'a
> {
1161 fn drop(&mut self) {
1163 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
1164 // panic code being inserted again.
1165 let self_vec
= (*self.string
).as_mut_vec();
1166 if self.start
<= self.end
&& self.end
<= self_vec
.len() {
1167 self_vec
.drain(self.start
..self.end
);
1173 #[unstable(feature = "drain", reason = "recently added")]
1174 impl<'a
> Iterator
for Drain
<'a
> {
1178 fn next(&mut self) -> Option
<char> {
1182 fn size_hint(&self) -> (usize, Option
<usize>) {
1183 self.iter
.size_hint()
1187 #[unstable(feature = "drain", reason = "recently added")]
1188 impl<'a
> DoubleEndedIterator
for Drain
<'a
> {
1190 fn next_back(&mut self) -> Option
<char> {
1191 self.iter
.next_back()