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")]
17 use core
::iter
::FromIterator
;
19 use core
::ops
::{self, Deref, Add, Index}
;
22 use core
::str::pattern
::Pattern
;
23 use rustc_unicode
::char::{decode_utf16, REPLACEMENT_CHARACTER}
;
24 use rustc_unicode
::str as unicode_str
;
26 use borrow
::{Cow, IntoCow}
;
27 use range
::RangeArgument
;
28 use str::{self, FromStr, Utf8Error, Chars}
;
32 /// A growable string stored as a UTF-8 encoded buffer.
33 #[derive(Clone, PartialOrd, Eq, Ord)]
34 #[stable(feature = "rust1", since = "1.0.0")]
39 /// A possible error value from the `String::from_utf8` function.
40 #[stable(feature = "rust1", since = "1.0.0")]
42 pub struct FromUtf8Error
{
47 /// A possible error value from the `String::from_utf16` function.
48 #[stable(feature = "rust1", since = "1.0.0")]
50 pub struct FromUtf16Error(());
53 /// Creates a new string buffer initialized with the empty string.
58 /// let mut s = String::new();
61 #[stable(feature = "rust1", since = "1.0.0")]
62 pub fn new() -> String
{
68 /// Creates a new string buffer with the given capacity.
69 /// The string will be able to hold exactly `capacity` bytes without
70 /// reallocating. If `capacity` is 0, the string will not allocate.
75 /// let mut s = String::with_capacity(10);
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub fn with_capacity(capacity
: usize) -> String
{
81 vec
: Vec
::with_capacity(capacity
),
85 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
86 // required for this method definition, is not available. Since we don't
87 // require this method for testing purposes, I'll just stub it
88 // NB see the slice::hack module in slice.rs for more information
91 pub fn from_str(_
: &str) -> String
{
92 panic
!("not available with cfg(test)");
95 /// Returns the vector as a string buffer, if possible, taking care not to
100 /// If the given vector is not valid UTF-8, then the original vector and the
101 /// corresponding error is returned.
106 /// let hello_vec = vec![104, 101, 108, 108, 111];
107 /// let s = String::from_utf8(hello_vec).unwrap();
108 /// assert_eq!(s, "hello");
110 /// let invalid_vec = vec![240, 144, 128];
111 /// let s = String::from_utf8(invalid_vec).err().unwrap();
112 /// let err = s.utf8_error();
113 /// assert_eq!(s.into_bytes(), [240, 144, 128]);
116 #[stable(feature = "rust1", since = "1.0.0")]
117 pub fn from_utf8(vec
: Vec
<u8>) -> Result
<String
, FromUtf8Error
> {
118 match str::from_utf8(&vec
) {
119 Ok(..) => Ok(String { vec: vec }
),
120 Err(e
) => Err(FromUtf8Error { bytes: vec, error: e }
)
124 /// Converts a vector of bytes to a new UTF-8 string.
125 /// Any invalid UTF-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
130 /// let input = b"Hello \xF0\x90\x80World";
131 /// let output = String::from_utf8_lossy(input);
132 /// assert_eq!(output, "Hello \u{FFFD}World");
134 #[stable(feature = "rust1", since = "1.0.0")]
135 pub fn from_utf8_lossy
<'a
>(v
: &'a
[u8]) -> Cow
<'a
, str> {
137 match str::from_utf8(v
) {
138 Ok(s
) => return Cow
::Borrowed(s
),
139 Err(e
) => i
= e
.valid_up_to(),
142 const TAG_CONT_U8
: u8 = 128;
143 const REPLACEMENT
: &'
static [u8] = b
"\xEF\xBF\xBD"; // U+FFFD in UTF-8
145 fn unsafe_get(xs
: &[u8], i
: usize) -> u8 {
146 unsafe { *xs.get_unchecked(i) }
148 fn safe_get(xs
: &[u8], i
: usize, total
: usize) -> u8 {
156 let mut res
= String
::with_capacity(total
);
160 res
.as_mut_vec().push_all(&v
[..i
])
164 // subseqidx is the index of the first byte of the subsequence we're
165 // looking at. It's used to copy a bunch of contiguous good codepoints
166 // at once instead of copying them one by one.
167 let mut subseqidx
= i
;
171 let byte
= unsafe_get(v
, i
);
174 macro_rules
! error
{ () => ({
177 res
.as_mut_vec().push_all(&v
[subseqidx
..i_
]);
180 res
.as_mut_vec().push_all(REPLACEMENT
);
185 // subseqidx handles this
187 let w
= unicode_str
::utf8_char_width(byte
);
191 if safe_get(v
, i
, total
) & 192 != TAG_CONT_U8
{
198 match (byte
, safe_get(v
, i
, total
)) {
199 (0xE0 , 0xA0 ... 0xBF) => (),
200 (0xE1 ... 0xEC, 0x80 ... 0xBF) => (),
201 (0xED , 0x80 ... 0x9F) => (),
202 (0xEE ... 0xEF, 0x80 ... 0xBF) => (),
209 if safe_get(v
, i
, total
) & 192 != TAG_CONT_U8
{
216 match (byte
, safe_get(v
, i
, total
)) {
217 (0xF0 , 0x90 ... 0xBF) => (),
218 (0xF1 ... 0xF3, 0x80 ... 0xBF) => (),
219 (0xF4 , 0x80 ... 0x8F) => (),
226 if safe_get(v
, i
, total
) & 192 != TAG_CONT_U8
{
231 if safe_get(v
, i
, total
) & 192 != TAG_CONT_U8
{
244 if subseqidx
< total
{
246 res
.as_mut_vec().push_all(&v
[subseqidx
..total
])
252 /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
253 /// if `v` contains any invalid data.
259 /// let mut v = &mut [0xD834, 0xDD1E, 0x006d, 0x0075,
260 /// 0x0073, 0x0069, 0x0063];
261 /// assert_eq!(String::from_utf16(v).unwrap(),
262 /// "𝄞music".to_string());
264 /// // 𝄞mu<invalid>ic
266 /// assert!(String::from_utf16(v).is_err());
268 #[stable(feature = "rust1", since = "1.0.0")]
269 pub fn from_utf16(v
: &[u16]) -> Result
<String
, FromUtf16Error
> {
270 decode_utf16(v
.iter().cloned()).collect
::<Result
<_
, _
>>().map_err(|_
| FromUtf16Error(()))
273 /// Decode a UTF-16 encoded vector `v` into a string, replacing
274 /// invalid data with the replacement character (U+FFFD).
279 /// // 𝄞mus<invalid>ic<invalid>
280 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
281 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
284 /// assert_eq!(String::from_utf16_lossy(v),
285 /// "𝄞mus\u{FFFD}ic\u{FFFD}".to_string());
288 #[stable(feature = "rust1", since = "1.0.0")]
289 pub fn from_utf16_lossy(v
: &[u16]) -> String
{
290 decode_utf16(v
.iter().cloned()).map(|r
| r
.unwrap_or(REPLACEMENT_CHARACTER
)).collect()
293 /// Creates a new `String` from a length, capacity, and pointer.
297 /// This is _very_ unsafe because:
299 /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`. Therefore, this
300 /// function inherits all of its unsafety, see [its
301 /// documentation](../vec/struct.Vec.html#method.from_raw_parts)
302 /// for the invariants it expects, they also apply to this function.
303 /// * We assume that the `Vec` contains valid UTF-8.
305 #[stable(feature = "rust1", since = "1.0.0")]
306 pub unsafe fn from_raw_parts(buf
: *mut u8, length
: usize, capacity
: usize) -> String
{
308 vec
: Vec
::from_raw_parts(buf
, length
, capacity
),
312 /// Converts a vector of bytes to a new `String` without checking if
313 /// it contains valid UTF-8. This is unsafe because it assumes that
314 /// the UTF-8-ness of the vector has already been validated.
316 #[stable(feature = "rust1", since = "1.0.0")]
317 pub unsafe fn from_utf8_unchecked(bytes
: Vec
<u8>) -> String
{
318 String { vec: bytes }
321 /// Returns the underlying byte buffer, encoded as UTF-8.
326 /// let s = String::from("hello");
327 /// let bytes = s.into_bytes();
328 /// assert_eq!(bytes, [104, 101, 108, 108, 111]);
331 #[stable(feature = "rust1", since = "1.0.0")]
332 pub fn into_bytes(self) -> Vec
<u8> {
336 /// Extracts a string slice containing the entire string.
338 #[unstable(feature = "convert",
339 reason
= "waiting on RFC revision",
341 pub fn as_str(&self) -> &str {
345 /// Pushes the given string onto this string buffer.
350 /// let mut s = String::from("foo");
351 /// s.push_str("bar");
352 /// assert_eq!(s, "foobar");
355 #[stable(feature = "rust1", since = "1.0.0")]
356 pub fn push_str(&mut self, string
: &str) {
357 self.vec
.push_all(string
.as_bytes())
360 /// Returns the number of bytes that this string buffer can hold without
366 /// let s = String::with_capacity(10);
367 /// assert!(s.capacity() >= 10);
370 #[stable(feature = "rust1", since = "1.0.0")]
371 pub fn capacity(&self) -> usize {
375 /// Reserves capacity for at least `additional` more bytes to be inserted
376 /// in the given `String`. The collection may reserve more space to avoid
377 /// frequent reallocations.
381 /// Panics if the new capacity overflows `usize`.
386 /// let mut s = String::new();
388 /// assert!(s.capacity() >= 10);
391 #[stable(feature = "rust1", since = "1.0.0")]
392 pub fn reserve(&mut self, additional
: usize) {
393 self.vec
.reserve(additional
)
396 /// Reserves the minimum capacity for exactly `additional` more bytes to be
397 /// inserted in the given `String`. Does nothing if the capacity is already
400 /// Note that the allocator may give the collection more space than it
401 /// requests. Therefore capacity can not be relied upon to be precisely
402 /// minimal. Prefer `reserve` if future insertions are expected.
406 /// Panics if the new capacity overflows `usize`.
411 /// let mut s = String::new();
412 /// s.reserve_exact(10);
413 /// assert!(s.capacity() >= 10);
416 #[stable(feature = "rust1", since = "1.0.0")]
417 pub fn reserve_exact(&mut self, additional
: usize) {
418 self.vec
.reserve_exact(additional
)
421 /// Shrinks the capacity of this string buffer to match its length.
426 /// let mut s = String::from("foo");
428 /// assert!(s.capacity() >= 100);
429 /// s.shrink_to_fit();
430 /// assert_eq!(s.capacity(), 3);
433 #[stable(feature = "rust1", since = "1.0.0")]
434 pub fn shrink_to_fit(&mut self) {
435 self.vec
.shrink_to_fit()
438 /// Adds the given character to the end of the string.
443 /// let mut s = String::from("abc");
447 /// assert_eq!(s, "abc123");
450 #[stable(feature = "rust1", since = "1.0.0")]
451 pub fn push(&mut self, ch
: char) {
452 match ch
.len_utf8() {
453 1 => self.vec
.push(ch
as u8),
455 let cur_len
= self.len();
456 // This may use up to 4 bytes.
457 self.vec
.reserve(ch_len
);
460 // Attempt to not use an intermediate buffer by just pushing bytes
461 // directly onto this string.
462 let slice
= slice
::from_raw_parts_mut (
463 self.vec
.as_mut_ptr().offset(cur_len
as isize),
466 let used
= ch
.encode_utf8(slice
).unwrap_or(0);
467 self.vec
.set_len(cur_len
+ used
);
473 /// Works with the underlying buffer as a byte slice.
478 /// let s = String::from("hello");
479 /// assert_eq!(s.as_bytes(), [104, 101, 108, 108, 111]);
482 #[stable(feature = "rust1", since = "1.0.0")]
483 pub fn as_bytes(&self) -> &[u8] {
487 /// Shortens a string to the specified length.
491 /// Panics if `new_len` > current length,
492 /// or if `new_len` is not a character boundary.
497 /// let mut s = String::from("hello");
499 /// assert_eq!(s, "he");
502 #[stable(feature = "rust1", since = "1.0.0")]
503 pub fn truncate(&mut self, new_len
: usize) {
504 assert
!(self.is_char_boundary(new_len
));
505 self.vec
.truncate(new_len
)
508 /// Removes the last character from the string buffer and returns it.
509 /// Returns `None` if this string buffer is empty.
514 /// let mut s = String::from("foo");
515 /// assert_eq!(s.pop(), Some('o'));
516 /// assert_eq!(s.pop(), Some('o'));
517 /// assert_eq!(s.pop(), Some('f'));
518 /// assert_eq!(s.pop(), None);
521 #[stable(feature = "rust1", since = "1.0.0")]
522 pub fn pop(&mut self) -> Option
<char> {
523 let len
= self.len();
528 let ch
= self.char_at_reverse(len
);
530 self.vec
.set_len(len
- ch
.len_utf8());
535 /// Removes the character from the string buffer at byte position `idx` and
540 /// This is an O(n) operation as it requires copying every element in the
545 /// If `idx` does not lie on a character boundary, or if it is out of
546 /// bounds, then this function will panic.
551 /// let mut s = String::from("foo");
552 /// assert_eq!(s.remove(0), 'f');
553 /// assert_eq!(s.remove(1), 'o');
554 /// assert_eq!(s.remove(0), 'o');
557 #[stable(feature = "rust1", since = "1.0.0")]
558 pub fn remove(&mut self, idx
: usize) -> char {
559 let len
= self.len();
562 let ch
= self.char_at(idx
);
563 let next
= idx
+ ch
.len_utf8();
565 ptr
::copy(self.vec
.as_ptr().offset(next
as isize),
566 self.vec
.as_mut_ptr().offset(idx
as isize),
568 self.vec
.set_len(len
- (next
- idx
));
573 /// Inserts a character into the string buffer at byte position `idx`.
577 /// This is an O(n) operation as it requires copying every element in the
582 /// If `idx` does not lie on a character boundary or is out of bounds, then
583 /// this function will panic.
585 #[stable(feature = "rust1", since = "1.0.0")]
586 pub fn insert(&mut self, idx
: usize, ch
: char) {
587 let len
= self.len();
589 assert
!(self.is_char_boundary(idx
));
591 let mut bits
= [0; 4];
592 let amt
= ch
.encode_utf8(&mut bits
).unwrap();
595 ptr
::copy(self.vec
.as_ptr().offset(idx
as isize),
596 self.vec
.as_mut_ptr().offset((idx
+ amt
) as isize),
598 ptr
::copy(bits
.as_ptr(),
599 self.vec
.as_mut_ptr().offset(idx
as isize),
601 self.vec
.set_len(len
+ amt
);
605 /// Views the string buffer as a mutable sequence of bytes.
607 /// This is unsafe because it does not check
608 /// to ensure that the resulting string will be valid UTF-8.
613 /// let mut s = String::from("hello");
615 /// let vec = s.as_mut_vec();
616 /// assert!(vec == &[104, 101, 108, 108, 111]);
619 /// assert_eq!(s, "olleh");
622 #[stable(feature = "rust1", since = "1.0.0")]
623 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec
<u8> {
627 /// Returns the number of bytes in this string.
632 /// let a = "foo".to_string();
633 /// assert_eq!(a.len(), 3);
636 #[stable(feature = "rust1", since = "1.0.0")]
637 pub fn len(&self) -> usize { self.vec.len() }
639 /// Returns true if the string contains no bytes
644 /// let mut v = String::new();
645 /// assert!(v.is_empty());
647 /// assert!(!v.is_empty());
650 #[stable(feature = "rust1", since = "1.0.0")]
651 pub fn is_empty(&self) -> bool { self.len() == 0 }
653 /// Truncates the string, returning it to 0 length.
658 /// let mut s = "foo".to_string();
660 /// assert!(s.is_empty());
663 #[stable(feature = "rust1", since = "1.0.0")]
664 pub fn clear(&mut self) {
668 /// Create a draining iterator that removes the specified range in the string
669 /// and yields the removed chars from start to end. The element range is
670 /// removed even if the iterator is not consumed until the end.
674 /// Panics if the starting point or end point are not on character boundaries,
675 /// or if they are out of bounds.
680 /// #![feature(drain)]
682 /// let mut s = String::from("α is alpha, β is beta");
683 /// let beta_offset = s.find('β').unwrap_or(s.len());
685 /// // Remove the range up until the β from the string
686 /// let t: String = s.drain(..beta_offset).collect();
687 /// assert_eq!(t, "α is alpha, ");
688 /// assert_eq!(s, "β is beta");
690 /// // A full range clears the string
692 /// assert_eq!(s, "");
694 #[unstable(feature = "drain",
695 reason
= "recently added, matches RFC",
697 pub fn drain
<R
>(&mut self, range
: R
) -> Drain
where R
: RangeArgument
<usize> {
700 // The String version of Drain does not have the memory safety issues
701 // of the vector version. The data is just plain bytes.
702 // Because the range removal happens in Drop, if the Drain iterator is leaked,
703 // the removal will not happen.
704 let len
= self.len();
705 let start
= *range
.start().unwrap_or(&0);
706 let end
= *range
.end().unwrap_or(&len
);
708 // Take out two simultaneous borrows. The &mut String won't be accessed
709 // until iteration is over, in Drop.
710 let self_ptr
= self as *mut _
;
711 // slicing does the appropriate bounds checks
712 let chars_iter
= self[start
..end
].chars();
722 /// Converts the string into `Box<str>`.
724 /// Note that this will drop any excess capacity.
725 #[stable(feature = "box_str", since = "1.4.0")]
726 pub fn into_boxed_str(self) -> Box
<str> {
727 let slice
= self.vec
.into_boxed_slice();
728 unsafe { mem::transmute::<Box<[u8]>, Box<str>>(slice) }
731 /// Converts the string into `Box<str>`.
733 /// Note that this will drop any excess capacity.
734 #[unstable(feature = "box_str2",
735 reason
= "recently added, matches RFC",
737 #[deprecated(since = "1.4.0", reason = "renamed to `into_boxed_str`")]
738 pub fn into_boxed_slice(self) -> Box
<str> {
739 self.into_boxed_str()
744 /// Consumes this error, returning the bytes that were attempted to make a
746 #[stable(feature = "rust1", since = "1.0.0")]
747 pub fn into_bytes(self) -> Vec
<u8> { self.bytes }
749 /// Access the underlying UTF8-error that was the cause of this error.
750 #[stable(feature = "rust1", since = "1.0.0")]
751 pub fn utf8_error(&self) -> Utf8Error { self.error }
754 #[stable(feature = "rust1", since = "1.0.0")]
755 impl fmt
::Display
for FromUtf8Error
{
756 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
757 fmt
::Display
::fmt(&self.error
, f
)
761 #[stable(feature = "rust1", since = "1.0.0")]
762 impl fmt
::Display
for FromUtf16Error
{
763 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
764 fmt
::Display
::fmt("invalid utf-16: lone surrogate found", f
)
768 #[stable(feature = "rust1", since = "1.0.0")]
769 impl FromIterator
<char> for String
{
770 fn from_iter
<I
: IntoIterator
<Item
=char>>(iterable
: I
) -> String
{
771 let mut buf
= String
::new();
772 buf
.extend(iterable
);
777 #[stable(feature = "rust1", since = "1.0.0")]
778 impl<'a
> FromIterator
<&'a
str> for String
{
779 fn from_iter
<I
: IntoIterator
<Item
=&'a
str>>(iterable
: I
) -> String
{
780 let mut buf
= String
::new();
781 buf
.extend(iterable
);
786 #[stable(feature = "extend_string", since = "1.4.0")]
787 impl FromIterator
<String
> for String
{
788 fn from_iter
<I
: IntoIterator
<Item
=String
>>(iterable
: I
) -> String
{
789 let mut buf
= String
::new();
790 buf
.extend(iterable
);
795 #[stable(feature = "rust1", since = "1.0.0")]
796 impl Extend
<char> for String
{
797 fn extend
<I
: IntoIterator
<Item
=char>>(&mut self, iterable
: I
) {
798 let iterator
= iterable
.into_iter();
799 let (lower_bound
, _
) = iterator
.size_hint();
800 self.reserve(lower_bound
);
807 #[stable(feature = "extend_ref", since = "1.2.0")]
808 impl<'a
> Extend
<&'a
char> for String
{
809 fn extend
<I
: IntoIterator
<Item
=&'a
char>>(&mut self, iterable
: I
) {
810 self.extend(iterable
.into_iter().cloned());
814 #[stable(feature = "rust1", since = "1.0.0")]
815 impl<'a
> Extend
<&'a
str> for String
{
816 fn extend
<I
: IntoIterator
<Item
=&'a
str>>(&mut self, iterable
: I
) {
823 #[stable(feature = "extend_string", since = "1.4.0")]
824 impl Extend
<String
> for String
{
825 fn extend
<I
: IntoIterator
<Item
=String
>>(&mut self, iterable
: I
) {
832 /// A convenience impl that delegates to the impl for `&str`
833 impl<'a
, 'b
> Pattern
<'a
> for &'b String
{
834 type Searcher
= <&'b
str as Pattern
<'a
>>::Searcher
;
836 fn into_searcher(self, haystack
: &'a
str) -> <&'b
str as Pattern
<'a
>>::Searcher
{
837 self[..].into_searcher(haystack
)
841 fn is_contained_in(self, haystack
: &'a
str) -> bool
{
842 self[..].is_contained_in(haystack
)
846 fn is_prefix_of(self, haystack
: &'a
str) -> bool
{
847 self[..].is_prefix_of(haystack
)
851 #[stable(feature = "rust1", since = "1.0.0")]
852 impl PartialEq
for String
{
854 fn eq(&self, other
: &String
) -> bool { PartialEq::eq(&self[..], &other[..]) }
856 fn ne(&self, other
: &String
) -> bool { PartialEq::ne(&self[..], &other[..]) }
859 macro_rules
! impl_eq
{
860 ($lhs
:ty
, $rhs
: ty
) => {
861 #[stable(feature = "rust1", since = "1.0.0")]
862 impl<'a
> PartialEq
<$rhs
> for $lhs
{
864 fn eq(&self, other
: &$rhs
) -> bool { PartialEq::eq(&self[..], &other[..]) }
866 fn ne(&self, other
: &$rhs
) -> bool { PartialEq::ne(&self[..], &other[..]) }
869 #[stable(feature = "rust1", since = "1.0.0")]
870 impl<'a
> PartialEq
<$lhs
> for $rhs
{
872 fn eq(&self, other
: &$lhs
) -> bool { PartialEq::eq(&self[..], &other[..]) }
874 fn ne(&self, other
: &$lhs
) -> bool { PartialEq::ne(&self[..], &other[..]) }
880 impl_eq
! { String, str }
881 impl_eq
! { String, &'a str }
882 impl_eq
! { Cow<'a, str>, str }
883 impl_eq
! { Cow<'a, str>, String }
885 #[stable(feature = "rust1", since = "1.0.0")]
886 impl<'a
, 'b
> PartialEq
<&'b
str> for Cow
<'a
, str> {
888 fn eq(&self, other
: &&'b
str) -> bool { PartialEq::eq(&self[..], &other[..]) }
890 fn ne(&self, other
: &&'b
str) -> bool { PartialEq::ne(&self[..], &other[..]) }
893 #[stable(feature = "rust1", since = "1.0.0")]
894 impl<'a
, 'b
> PartialEq
<Cow
<'a
, str>> for &'b
str {
896 fn eq(&self, other
: &Cow
<'a
, str>) -> bool { PartialEq::eq(&self[..], &other[..]) }
898 fn ne(&self, other
: &Cow
<'a
, str>) -> bool { PartialEq::ne(&self[..], &other[..]) }
901 #[stable(feature = "rust1", since = "1.0.0")]
902 impl Default
for String
{
904 #[stable(feature = "rust1", since = "1.0.0")]
905 fn default() -> String
{
910 #[stable(feature = "rust1", since = "1.0.0")]
911 impl fmt
::Display
for String
{
913 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
914 fmt
::Display
::fmt(&**self, f
)
918 #[stable(feature = "rust1", since = "1.0.0")]
919 impl fmt
::Debug
for String
{
921 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
922 fmt
::Debug
::fmt(&**self, f
)
926 #[stable(feature = "rust1", since = "1.0.0")]
927 impl hash
::Hash
for String
{
929 fn hash
<H
: hash
::Hasher
>(&self, hasher
: &mut H
) {
930 (**self).hash(hasher
)
934 #[stable(feature = "rust1", since = "1.0.0")]
935 impl<'a
> Add
<&'a
str> for String
{
936 type Output
= String
;
939 fn add(mut self, other
: &str) -> String
{
940 self.push_str(other
);
945 #[stable(feature = "rust1", since = "1.0.0")]
946 impl ops
::Index
<ops
::Range
<usize>> for String
{
950 fn index(&self, index
: ops
::Range
<usize>) -> &str {
954 #[stable(feature = "rust1", since = "1.0.0")]
955 impl ops
::Index
<ops
::RangeTo
<usize>> for String
{
959 fn index(&self, index
: ops
::RangeTo
<usize>) -> &str {
963 #[stable(feature = "rust1", since = "1.0.0")]
964 impl ops
::Index
<ops
::RangeFrom
<usize>> for String
{
968 fn index(&self, index
: ops
::RangeFrom
<usize>) -> &str {
972 #[stable(feature = "rust1", since = "1.0.0")]
973 impl ops
::Index
<ops
::RangeFull
> for String
{
977 fn index(&self, _index
: ops
::RangeFull
) -> &str {
978 unsafe { str::from_utf8_unchecked(&self.vec) }
982 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
983 impl ops
::IndexMut
<ops
::Range
<usize>> for String
{
985 fn index_mut(&mut self, index
: ops
::Range
<usize>) -> &mut str {
989 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
990 impl ops
::IndexMut
<ops
::RangeTo
<usize>> for String
{
992 fn index_mut(&mut self, index
: ops
::RangeTo
<usize>) -> &mut str {
996 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
997 impl ops
::IndexMut
<ops
::RangeFrom
<usize>> for String
{
999 fn index_mut(&mut self, index
: ops
::RangeFrom
<usize>) -> &mut str {
1000 &mut self[..][index
]
1003 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1004 impl ops
::IndexMut
<ops
::RangeFull
> for String
{
1006 fn index_mut(&mut self, _index
: ops
::RangeFull
) -> &mut str {
1007 unsafe { mem::transmute(&mut *self.vec) }
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 impl ops
::Deref
for String
{
1016 fn deref(&self) -> &str {
1017 unsafe { str::from_utf8_unchecked(&self.vec) }
1021 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1022 impl ops
::DerefMut
for String
{
1024 fn deref_mut(&mut self) -> &mut str {
1025 unsafe { mem::transmute(&mut *self.vec) }
1029 /// Error returned from `String::from`
1030 #[unstable(feature = "str_parse_error", reason = "may want to be replaced with \
1031 Void if it ever exists",
1033 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1034 pub struct ParseError(());
1036 #[stable(feature = "rust1", since = "1.0.0")]
1037 impl FromStr
for String
{
1038 type Err
= ParseError
;
1040 fn from_str(s
: &str) -> Result
<String
, ParseError
> {
1045 /// A generic trait for converting a value to a string
1046 #[stable(feature = "rust1", since = "1.0.0")]
1047 pub trait ToString
{
1048 /// Converts the value of `self` to an owned string
1049 #[stable(feature = "rust1", since = "1.0.0")]
1050 fn to_string(&self) -> String
;
1053 #[stable(feature = "rust1", since = "1.0.0")]
1054 impl<T
: fmt
::Display
+ ?Sized
> ToString
for T
{
1056 fn to_string(&self) -> String
{
1057 use core
::fmt
::Write
;
1058 let mut buf
= String
::new();
1059 let _
= buf
.write_fmt(format_args
!("{}", self));
1060 buf
.shrink_to_fit();
1065 #[stable(feature = "rust1", since = "1.0.0")]
1066 impl AsRef
<str> for String
{
1068 fn as_ref(&self) -> &str {
1073 #[stable(feature = "rust1", since = "1.0.0")]
1074 impl AsRef
<[u8]> for String
{
1076 fn as_ref(&self) -> &[u8] {
1081 #[stable(feature = "rust1", since = "1.0.0")]
1082 impl<'a
> From
<&'a
str> for String
{
1085 fn from(s
: &'a
str) -> String
{
1086 String { vec: <[_]>::to_vec(s.as_bytes()) }
1089 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1090 // required for this method definition, is not available. Since we don't
1091 // require this method for testing purposes, I'll just stub it
1092 // NB see the slice::hack module in slice.rs for more information
1095 fn from(_
: &str) -> String
{
1096 panic
!("not available with cfg(test)");
1100 #[stable(feature = "rust1", since = "1.0.0")]
1101 impl<'a
> From
<&'a
str> for Cow
<'a
, str> {
1103 fn from(s
: &'a
str) -> Cow
<'a
, str> {
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 impl<'a
> From
<String
> for Cow
<'a
, str> {
1111 fn from(s
: String
) -> Cow
<'a
, str> {
1116 #[stable(feature = "rust1", since = "1.0.0")]
1117 impl Into
<Vec
<u8>> for String
{
1118 fn into(self) -> Vec
<u8> {
1123 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`",
1125 impl IntoCow
<'
static, str> for String
{
1127 fn into_cow(self) -> Cow
<'
static, str> {
1132 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`",
1134 impl<'a
> IntoCow
<'a
, str> for &'a
str {
1136 fn into_cow(self) -> Cow
<'a
, str> {
1141 #[stable(feature = "rust1", since = "1.0.0")]
1142 impl fmt
::Write
for String
{
1144 fn write_str(&mut self, s
: &str) -> fmt
::Result
{
1150 fn write_char(&mut self, c
: char) -> fmt
::Result
{
1156 /// A draining iterator for `String`.
1157 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1158 pub struct Drain
<'a
> {
1159 /// Will be used as &'a mut String in the destructor
1160 string
: *mut String
,
1161 /// Start of part to remove
1163 /// End of part to remove
1165 /// Current remaining range to remove
1169 unsafe impl<'a
> Sync
for Drain
<'a
> {}
1170 unsafe impl<'a
> Send
for Drain
<'a
> {}
1172 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1173 impl<'a
> Drop
for Drain
<'a
> {
1174 fn drop(&mut self) {
1176 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
1177 // panic code being inserted again.
1178 let self_vec
= (*self.string
).as_mut_vec();
1179 if self.start
<= self.end
&& self.end
<= self_vec
.len() {
1180 self_vec
.drain(self.start
..self.end
);
1186 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1187 impl<'a
> Iterator
for Drain
<'a
> {
1191 fn next(&mut self) -> Option
<char> {
1195 fn size_hint(&self) -> (usize, Option
<usize>) {
1196 self.iter
.size_hint()
1200 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1201 impl<'a
> DoubleEndedIterator
for Drain
<'a
> {
1203 fn next_back(&mut self) -> Option
<char> {
1204 self.iter
.next_back()