]> git.lizzy.rs Git - rust.git/blob - src/libcollections/string.rs
Auto merge of #23861 - Manishearth:rollup, r=Manishearth
[rust.git] / src / libcollections / string.rs
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.
4 //
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.
10 //
11 // ignore-lexer-test FIXME #15679
12
13 //! An owned, growable string that enforces that its contents are valid UTF-8.
14
15 #![stable(feature = "rust1", since = "1.0.0")]
16
17 use core::prelude::*;
18
19 use core::default::Default;
20 use core::error::Error;
21 use core::fmt;
22 use core::hash;
23 use core::iter::{IntoIterator, FromIterator};
24 use core::mem;
25 use core::ops::{self, Deref, Add, Index};
26 use core::ptr;
27 use core::slice;
28 use core::str::Pattern;
29 use unicode::str as unicode_str;
30 use unicode::str::Utf16Item;
31
32 use borrow::{Cow, IntoCow};
33 use str::{self, FromStr, Utf8Error};
34 use vec::{DerefVec, Vec, as_vec};
35
36 /// A growable string stored as a UTF-8 encoded buffer.
37 #[derive(Clone, PartialOrd, Eq, Ord)]
38 #[stable(feature = "rust1", since = "1.0.0")]
39 pub struct String {
40     vec: Vec<u8>,
41 }
42
43 /// A possible error value from the `String::from_utf8` function.
44 #[stable(feature = "rust1", since = "1.0.0")]
45 #[derive(Debug)]
46 pub struct FromUtf8Error {
47     bytes: Vec<u8>,
48     error: Utf8Error,
49 }
50
51 /// A possible error value from the `String::from_utf16` function.
52 #[stable(feature = "rust1", since = "1.0.0")]
53 #[derive(Debug)]
54 pub struct FromUtf16Error(());
55
56 impl String {
57     /// Creates a new string buffer initialized with the empty string.
58     ///
59     /// # Examples
60     ///
61     /// ```
62     /// let mut s = String::new();
63     /// ```
64     #[inline]
65     #[stable(feature = "rust1", since = "1.0.0")]
66     pub fn new() -> String {
67         String {
68             vec: Vec::new(),
69         }
70     }
71
72     /// Creates a new string buffer with the given capacity.
73     /// The string will be able to hold exactly `capacity` bytes without
74     /// reallocating. If `capacity` is 0, the string will not allocate.
75     ///
76     /// # Examples
77     ///
78     /// ```
79     /// let mut s = String::with_capacity(10);
80     /// ```
81     #[inline]
82     #[stable(feature = "rust1", since = "1.0.0")]
83     pub fn with_capacity(capacity: usize) -> String {
84         String {
85             vec: Vec::with_capacity(capacity),
86         }
87     }
88
89     /// Creates a new string buffer from the given string.
90     ///
91     /// # Examples
92     ///
93     /// ```
94     /// # #![feature(collections, core)]
95     /// let s = String::from_str("hello");
96     /// assert_eq!(s.as_slice(), "hello");
97     /// ```
98     #[inline]
99     #[unstable(feature = "collections",
100                reason = "needs investigation to see if to_string() can match perf")]
101     #[cfg(not(test))]
102     pub fn from_str(string: &str) -> String {
103         String { vec: <[_]>::to_vec(string.as_bytes()) }
104     }
105
106     // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
107     // required for this method definition, is not available. Since we don't
108     // require this method for testing purposes, I'll just stub it
109     // NB see the slice::hack module in slice.rs for more information
110     #[inline]
111     #[cfg(test)]
112     pub fn from_str(_: &str) -> String {
113         panic!("not available with cfg(test)");
114     }
115
116     /// Returns the vector as a string buffer, if possible, taking care not to
117     /// copy it.
118     ///
119     /// # Failure
120     ///
121     /// If the given vector is not valid UTF-8, then the original vector and the
122     /// corresponding error is returned.
123     ///
124     /// # Examples
125     ///
126     /// ```
127     /// # #![feature(core)]
128     /// use std::str::Utf8Error;
129     ///
130     /// let hello_vec = vec![104, 101, 108, 108, 111];
131     /// let s = String::from_utf8(hello_vec).unwrap();
132     /// assert_eq!(s, "hello");
133     ///
134     /// let invalid_vec = vec![240, 144, 128];
135     /// let s = String::from_utf8(invalid_vec).err().unwrap();
136     /// assert_eq!(s.utf8_error(), Utf8Error::TooShort);
137     /// assert_eq!(s.into_bytes(), [240, 144, 128]);
138     /// ```
139     #[inline]
140     #[stable(feature = "rust1", since = "1.0.0")]
141     pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
142         match str::from_utf8(&vec) {
143             Ok(..) => Ok(String { vec: vec }),
144             Err(e) => Err(FromUtf8Error { bytes: vec, error: e })
145         }
146     }
147
148     /// Converts a vector of bytes to a new UTF-8 string.
149     /// Any invalid UTF-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
150     ///
151     /// # Examples
152     ///
153     /// ```
154     /// let input = b"Hello \xF0\x90\x80World";
155     /// let output = String::from_utf8_lossy(input);
156     /// assert_eq!(output, "Hello \u{FFFD}World");
157     /// ```
158     #[stable(feature = "rust1", since = "1.0.0")]
159     pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
160         let mut i = 0;
161         match str::from_utf8(v) {
162             Ok(s) => return Cow::Borrowed(s),
163             Err(e) => {
164                 if let Utf8Error::InvalidByte(firstbad) = e {
165                     i = firstbad;
166                 }
167             }
168         }
169
170         const TAG_CONT_U8: u8 = 128;
171         const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
172         let total = v.len();
173         fn unsafe_get(xs: &[u8], i: usize) -> u8 {
174             unsafe { *xs.get_unchecked(i) }
175         }
176         fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 {
177             if i >= total {
178                 0
179             } else {
180                 unsafe_get(xs, i)
181             }
182         }
183
184         let mut res = String::with_capacity(total);
185
186         if i > 0 {
187             unsafe {
188                 res.as_mut_vec().push_all(&v[..i])
189             };
190         }
191
192         // subseqidx is the index of the first byte of the subsequence we're looking at.
193         // It's used to copy a bunch of contiguous good codepoints at once instead of copying
194         // them one by one.
195         let mut subseqidx = i;
196
197         while i < total {
198             let i_ = i;
199             let byte = unsafe_get(v, i);
200             i += 1;
201
202             macro_rules! error { () => ({
203                 unsafe {
204                     if subseqidx != i_ {
205                         res.as_mut_vec().push_all(&v[subseqidx..i_]);
206                     }
207                     subseqidx = i;
208                     res.as_mut_vec().push_all(REPLACEMENT);
209                 }
210             })}
211
212             if byte < 128 {
213                 // subseqidx handles this
214             } else {
215                 let w = unicode_str::utf8_char_width(byte);
216
217                 match w {
218                     2 => {
219                         if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
220                             error!();
221                             continue;
222                         }
223                         i += 1;
224                     }
225                     3 => {
226                         match (byte, safe_get(v, i, total)) {
227                             (0xE0         , 0xA0 ... 0xBF) => (),
228                             (0xE1 ... 0xEC, 0x80 ... 0xBF) => (),
229                             (0xED         , 0x80 ... 0x9F) => (),
230                             (0xEE ... 0xEF, 0x80 ... 0xBF) => (),
231                             _ => {
232                                 error!();
233                                 continue;
234                             }
235                         }
236                         i += 1;
237                         if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
238                             error!();
239                             continue;
240                         }
241                         i += 1;
242                     }
243                     4 => {
244                         match (byte, safe_get(v, i, total)) {
245                             (0xF0         , 0x90 ... 0xBF) => (),
246                             (0xF1 ... 0xF3, 0x80 ... 0xBF) => (),
247                             (0xF4         , 0x80 ... 0x8F) => (),
248                             _ => {
249                                 error!();
250                                 continue;
251                             }
252                         }
253                         i += 1;
254                         if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
255                             error!();
256                             continue;
257                         }
258                         i += 1;
259                         if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
260                             error!();
261                             continue;
262                         }
263                         i += 1;
264                     }
265                     _ => {
266                         error!();
267                         continue;
268                     }
269                 }
270             }
271         }
272         if subseqidx < total {
273             unsafe {
274                 res.as_mut_vec().push_all(&v[subseqidx..total])
275             };
276         }
277         Cow::Owned(res)
278     }
279
280     /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
281     /// if `v` contains any invalid data.
282     ///
283     /// # Examples
284     ///
285     /// ```
286     /// // 𝄞music
287     /// let mut v = &mut [0xD834, 0xDD1E, 0x006d, 0x0075,
288     ///                   0x0073, 0x0069, 0x0063];
289     /// assert_eq!(String::from_utf16(v).unwrap(),
290     ///            "𝄞music".to_string());
291     ///
292     /// // 𝄞mu<invalid>ic
293     /// v[4] = 0xD800;
294     /// assert!(String::from_utf16(v).is_err());
295     /// ```
296     #[stable(feature = "rust1", since = "1.0.0")]
297     pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
298         let mut s = String::with_capacity(v.len());
299         for c in unicode_str::utf16_items(v) {
300             match c {
301                 Utf16Item::ScalarValue(c) => s.push(c),
302                 Utf16Item::LoneSurrogate(_) => return Err(FromUtf16Error(())),
303             }
304         }
305         Ok(s)
306     }
307
308     /// Decode a UTF-16 encoded vector `v` into a string, replacing
309     /// invalid data with the replacement character (U+FFFD).
310     ///
311     /// # Examples
312     ///
313     /// ```
314     /// // 𝄞mus<invalid>ic<invalid>
315     /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
316     ///           0x0073, 0xDD1E, 0x0069, 0x0063,
317     ///           0xD834];
318     ///
319     /// assert_eq!(String::from_utf16_lossy(v),
320     ///            "𝄞mus\u{FFFD}ic\u{FFFD}".to_string());
321     /// ```
322     #[inline]
323     #[stable(feature = "rust1", since = "1.0.0")]
324     pub fn from_utf16_lossy(v: &[u16]) -> String {
325         unicode_str::utf16_items(v).map(|c| c.to_char_lossy()).collect()
326     }
327
328     /// Creates a new `String` from a length, capacity, and pointer.
329     ///
330     /// This is unsafe because:
331     ///
332     /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`;
333     /// * We assume that the `Vec` contains valid UTF-8.
334     #[inline]
335     #[stable(feature = "rust1", since = "1.0.0")]
336     pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
337         String {
338             vec: Vec::from_raw_parts(buf, length, capacity),
339         }
340     }
341
342     /// Converts a vector of bytes to a new `String` without checking if
343     /// it contains valid UTF-8. This is unsafe because it assumes that
344     /// the UTF-8-ness of the vector has already been validated.
345     #[inline]
346     #[stable(feature = "rust1", since = "1.0.0")]
347     pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
348         String { vec: bytes }
349     }
350
351     /// Return the underlying byte buffer, encoded as UTF-8.
352     ///
353     /// # Examples
354     ///
355     /// ```
356     /// # #![feature(collections)]
357     /// let s = String::from_str("hello");
358     /// let bytes = s.into_bytes();
359     /// assert_eq!(bytes, [104, 101, 108, 108, 111]);
360     /// ```
361     #[inline]
362     #[stable(feature = "rust1", since = "1.0.0")]
363     pub fn into_bytes(self) -> Vec<u8> {
364         self.vec
365     }
366
367     /// Pushes the given string onto this string buffer.
368     ///
369     /// # Examples
370     ///
371     /// ```
372     /// # #![feature(collections)]
373     /// let mut s = String::from_str("foo");
374     /// s.push_str("bar");
375     /// assert_eq!(s, "foobar");
376     /// ```
377     #[inline]
378     #[stable(feature = "rust1", since = "1.0.0")]
379     pub fn push_str(&mut self, string: &str) {
380         self.vec.push_all(string.as_bytes())
381     }
382
383     /// Returns the number of bytes that this string buffer can hold without
384     /// reallocating.
385     ///
386     /// # Examples
387     ///
388     /// ```
389     /// let s = String::with_capacity(10);
390     /// assert!(s.capacity() >= 10);
391     /// ```
392     #[inline]
393     #[stable(feature = "rust1", since = "1.0.0")]
394     pub fn capacity(&self) -> usize {
395         self.vec.capacity()
396     }
397
398     /// Reserves capacity for at least `additional` more bytes to be inserted
399     /// in the given `String`. The collection may reserve more space to avoid
400     /// frequent reallocations.
401     ///
402     /// # Panics
403     ///
404     /// Panics if the new capacity overflows `usize`.
405     ///
406     /// # Examples
407     ///
408     /// ```
409     /// let mut s = String::new();
410     /// s.reserve(10);
411     /// assert!(s.capacity() >= 10);
412     /// ```
413     #[inline]
414     #[stable(feature = "rust1", since = "1.0.0")]
415     pub fn reserve(&mut self, additional: usize) {
416         self.vec.reserve(additional)
417     }
418
419     /// Reserves the minimum capacity for exactly `additional` more bytes to be
420     /// inserted in the given `String`. Does nothing if the capacity is already
421     /// sufficient.
422     ///
423     /// Note that the allocator may give the collection more space than it
424     /// requests. Therefore capacity can not be relied upon to be precisely
425     /// minimal. Prefer `reserve` if future insertions are expected.
426     ///
427     /// # Panics
428     ///
429     /// Panics if the new capacity overflows `usize`.
430     ///
431     /// # Examples
432     ///
433     /// ```
434     /// let mut s = String::new();
435     /// s.reserve(10);
436     /// assert!(s.capacity() >= 10);
437     /// ```
438     #[inline]
439     #[stable(feature = "rust1", since = "1.0.0")]
440     pub fn reserve_exact(&mut self, additional: usize) {
441         self.vec.reserve_exact(additional)
442     }
443
444     /// Shrinks the capacity of this string buffer to match its length.
445     ///
446     /// # Examples
447     ///
448     /// ```
449     /// # #![feature(collections)]
450     /// let mut s = String::from_str("foo");
451     /// s.reserve(100);
452     /// assert!(s.capacity() >= 100);
453     /// s.shrink_to_fit();
454     /// assert_eq!(s.capacity(), 3);
455     /// ```
456     #[inline]
457     #[stable(feature = "rust1", since = "1.0.0")]
458     pub fn shrink_to_fit(&mut self) {
459         self.vec.shrink_to_fit()
460     }
461
462     /// Adds the given character to the end of the string.
463     ///
464     /// # Examples
465     ///
466     /// ```
467     /// # #![feature(collections)]
468     /// let mut s = String::from_str("abc");
469     /// s.push('1');
470     /// s.push('2');
471     /// s.push('3');
472     /// assert_eq!(s, "abc123");
473     /// ```
474     #[inline]
475     #[stable(feature = "rust1", since = "1.0.0")]
476     pub fn push(&mut self, ch: char) {
477         if (ch as u32) < 0x80 {
478             self.vec.push(ch as u8);
479             return;
480         }
481
482         let cur_len = self.len();
483         // This may use up to 4 bytes.
484         self.vec.reserve(4);
485
486         unsafe {
487             // Attempt to not use an intermediate buffer by just pushing bytes
488             // directly onto this string.
489             let slice = slice::from_raw_parts_mut (
490                 self.vec.as_mut_ptr().offset(cur_len as isize),
491                 4
492             );
493             let used = ch.encode_utf8(slice).unwrap_or(0);
494             self.vec.set_len(cur_len + used);
495         }
496     }
497
498     /// Works with the underlying buffer as a byte slice.
499     ///
500     /// # Examples
501     ///
502     /// ```
503     /// # #![feature(collections)]
504     /// let s = String::from_str("hello");
505     /// let b: &[_] = &[104, 101, 108, 108, 111];
506     /// assert_eq!(s.as_bytes(), b);
507     /// ```
508     #[inline]
509     #[stable(feature = "rust1", since = "1.0.0")]
510     pub fn as_bytes(&self) -> &[u8] {
511         &self.vec
512     }
513
514     /// Shortens a string to the specified length.
515     ///
516     /// # Panics
517     ///
518     /// Panics if `new_len` > current length,
519     /// or if `new_len` is not a character boundary.
520     ///
521     /// # Examples
522     ///
523     /// ```
524     /// # #![feature(collections)]
525     /// let mut s = String::from_str("hello");
526     /// s.truncate(2);
527     /// assert_eq!(s, "he");
528     /// ```
529     #[inline]
530     #[stable(feature = "rust1", since = "1.0.0")]
531     pub fn truncate(&mut self, new_len: usize) {
532         assert!(self.is_char_boundary(new_len));
533         self.vec.truncate(new_len)
534     }
535
536     /// Removes the last character from the string buffer and returns it.
537     /// Returns `None` if this string buffer is empty.
538     ///
539     /// # Examples
540     ///
541     /// ```
542     /// # #![feature(collections)]
543     /// let mut s = String::from_str("foo");
544     /// assert_eq!(s.pop(), Some('o'));
545     /// assert_eq!(s.pop(), Some('o'));
546     /// assert_eq!(s.pop(), Some('f'));
547     /// assert_eq!(s.pop(), None);
548     /// ```
549     #[inline]
550     #[stable(feature = "rust1", since = "1.0.0")]
551     pub fn pop(&mut self) -> Option<char> {
552         let len = self.len();
553         if len == 0 {
554             return None
555         }
556
557         let ch = self.char_at_reverse(len);
558         unsafe {
559             self.vec.set_len(len - ch.len_utf8());
560         }
561         Some(ch)
562     }
563
564     /// Removes the character from the string buffer at byte position `idx` and
565     /// returns it.
566     ///
567     /// # Warning
568     ///
569     /// This is an O(n) operation as it requires copying every element in the
570     /// buffer.
571     ///
572     /// # Panics
573     ///
574     /// If `idx` does not lie on a character boundary, or if it is out of
575     /// bounds, then this function will panic.
576     ///
577     /// # Examples
578     ///
579     /// ```
580     /// # #![feature(collections)]
581     /// let mut s = String::from_str("foo");
582     /// assert_eq!(s.remove(0), 'f');
583     /// assert_eq!(s.remove(1), 'o');
584     /// assert_eq!(s.remove(0), 'o');
585     /// ```
586     #[inline]
587     #[stable(feature = "rust1", since = "1.0.0")]
588     pub fn remove(&mut self, idx: usize) -> char {
589         let len = self.len();
590         assert!(idx <= len);
591
592         let ch = self.char_at(idx);
593         let next = idx + ch.len_utf8();
594         unsafe {
595             ptr::copy(self.vec.as_mut_ptr().offset(idx as isize),
596                       self.vec.as_ptr().offset(next as isize),
597                       len - next);
598             self.vec.set_len(len - (next - idx));
599         }
600         ch
601     }
602
603     /// Insert a character into the string buffer at byte position `idx`.
604     ///
605     /// # Warning
606     ///
607     /// This is an O(n) operation as it requires copying every element in the
608     /// buffer.
609     ///
610     /// # Panics
611     ///
612     /// If `idx` does not lie on a character boundary or is out of bounds, then
613     /// this function will panic.
614     #[inline]
615     #[stable(feature = "rust1", since = "1.0.0")]
616     pub fn insert(&mut self, idx: usize, ch: char) {
617         let len = self.len();
618         assert!(idx <= len);
619         assert!(self.is_char_boundary(idx));
620         self.vec.reserve(4);
621         let mut bits = [0; 4];
622         let amt = ch.encode_utf8(&mut bits).unwrap();
623
624         unsafe {
625             ptr::copy(self.vec.as_mut_ptr().offset((idx + amt) as isize),
626                       self.vec.as_ptr().offset(idx as isize),
627                       len - idx);
628             ptr::copy(self.vec.as_mut_ptr().offset(idx as isize),
629                       bits.as_ptr(),
630                       amt);
631             self.vec.set_len(len + amt);
632         }
633     }
634
635     /// Views the string buffer as a mutable sequence of bytes.
636     ///
637     /// This is unsafe because it does not check
638     /// to ensure that the resulting string will be valid UTF-8.
639     ///
640     /// # Examples
641     ///
642     /// ```
643     /// # #![feature(collections)]
644     /// let mut s = String::from_str("hello");
645     /// unsafe {
646     ///     let vec = s.as_mut_vec();
647     ///     assert!(vec == &[104, 101, 108, 108, 111]);
648     ///     vec.reverse();
649     /// }
650     /// assert_eq!(s, "olleh");
651     /// ```
652     #[inline]
653     #[stable(feature = "rust1", since = "1.0.0")]
654     pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
655         &mut self.vec
656     }
657
658     /// Return the number of bytes in this string.
659     ///
660     /// # Examples
661     ///
662     /// ```
663     /// let a = "foo".to_string();
664     /// assert_eq!(a.len(), 3);
665     /// ```
666     #[inline]
667     #[stable(feature = "rust1", since = "1.0.0")]
668     pub fn len(&self) -> usize { self.vec.len() }
669
670     /// Returns true if the string contains no bytes
671     ///
672     /// # Examples
673     ///
674     /// ```
675     /// let mut v = String::new();
676     /// assert!(v.is_empty());
677     /// v.push('a');
678     /// assert!(!v.is_empty());
679     /// ```
680     #[inline]
681     #[stable(feature = "rust1", since = "1.0.0")]
682     pub fn is_empty(&self) -> bool { self.len() == 0 }
683
684     /// Truncates the string, returning it to 0 length.
685     ///
686     /// # Examples
687     ///
688     /// ```
689     /// let mut s = "foo".to_string();
690     /// s.clear();
691     /// assert!(s.is_empty());
692     /// ```
693     #[inline]
694     #[stable(feature = "rust1", since = "1.0.0")]
695     pub fn clear(&mut self) {
696         self.vec.clear()
697     }
698 }
699
700 impl FromUtf8Error {
701     /// Consume this error, returning the bytes that were attempted to make a
702     /// `String` with.
703     #[stable(feature = "rust1", since = "1.0.0")]
704     pub fn into_bytes(self) -> Vec<u8> { self.bytes }
705
706     /// Access the underlying UTF8-error that was the cause of this error.
707     #[stable(feature = "rust1", since = "1.0.0")]
708     pub fn utf8_error(&self) -> Utf8Error { self.error }
709 }
710
711 #[stable(feature = "rust1", since = "1.0.0")]
712 impl fmt::Display for FromUtf8Error {
713     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
714         fmt::Display::fmt(&self.error, f)
715     }
716 }
717
718 #[stable(feature = "rust1", since = "1.0.0")]
719 impl Error for FromUtf8Error {
720     fn description(&self) -> &str { "invalid utf-8" }
721 }
722
723 #[stable(feature = "rust1", since = "1.0.0")]
724 impl fmt::Display for FromUtf16Error {
725     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
726         fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
727     }
728 }
729
730 #[stable(feature = "rust1", since = "1.0.0")]
731 impl Error for FromUtf16Error {
732     fn description(&self) -> &str { "invalid utf-16" }
733 }
734
735 #[stable(feature = "rust1", since = "1.0.0")]
736 impl FromIterator<char> for String {
737     fn from_iter<I: IntoIterator<Item=char>>(iter: I) -> String {
738         let mut buf = String::new();
739         buf.extend(iter);
740         buf
741     }
742 }
743
744 #[stable(feature = "rust1", since = "1.0.0")]
745 impl<'a> FromIterator<&'a str> for String {
746     fn from_iter<I: IntoIterator<Item=&'a str>>(iter: I) -> String {
747         let mut buf = String::new();
748         buf.extend(iter);
749         buf
750     }
751 }
752
753 #[unstable(feature = "collections",
754            reason = "waiting on Extend stabilization")]
755 impl Extend<char> for String {
756     fn extend<I: IntoIterator<Item=char>>(&mut self, iterable: I) {
757         let iterator = iterable.into_iter();
758         let (lower_bound, _) = iterator.size_hint();
759         self.reserve(lower_bound);
760         for ch in iterator {
761             self.push(ch)
762         }
763     }
764 }
765
766 #[unstable(feature = "collections",
767            reason = "waiting on Extend stabilization")]
768 impl<'a> Extend<&'a str> for String {
769     fn extend<I: IntoIterator<Item=&'a str>>(&mut self, iterable: I) {
770         let iterator = iterable.into_iter();
771         // A guess that at least one byte per iterator element will be needed.
772         let (lower_bound, _) = iterator.size_hint();
773         self.reserve(lower_bound);
774         for s in iterator {
775             self.push_str(s)
776         }
777     }
778 }
779
780 /// A convenience impl that delegates to the impl for `&str`
781 impl<'a, 'b> Pattern<'a> for &'b String {
782     type Searcher = <&'b str as Pattern<'a>>::Searcher;
783
784     fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
785         self[..].into_searcher(haystack)
786     }
787
788     #[inline]
789     fn is_contained_in(self, haystack: &'a str) -> bool {
790         self[..].is_contained_in(haystack)
791     }
792
793     #[inline]
794     fn is_prefix_of(self, haystack: &'a str) -> bool {
795         self[..].is_prefix_of(haystack)
796     }
797 }
798
799 #[stable(feature = "rust1", since = "1.0.0")]
800 impl PartialEq for String {
801     #[inline]
802     fn eq(&self, other: &String) -> bool { PartialEq::eq(&**self, &**other) }
803     #[inline]
804     fn ne(&self, other: &String) -> bool { PartialEq::ne(&**self, &**other) }
805 }
806
807 macro_rules! impl_eq {
808     ($lhs:ty, $rhs: ty) => {
809         #[stable(feature = "rust1", since = "1.0.0")]
810         impl<'a> PartialEq<$rhs> for $lhs {
811             #[inline]
812             fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
813             #[inline]
814             fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
815         }
816
817         #[stable(feature = "rust1", since = "1.0.0")]
818         impl<'a> PartialEq<$lhs> for $rhs {
819             #[inline]
820             fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) }
821             #[inline]
822             fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) }
823         }
824
825     }
826 }
827
828 impl_eq! { String, &'a str }
829 impl_eq! { Cow<'a, str>, String }
830
831 #[stable(feature = "rust1", since = "1.0.0")]
832 impl<'a, 'b> PartialEq<&'b str> for Cow<'a, str> {
833     #[inline]
834     fn eq(&self, other: &&'b str) -> bool { PartialEq::eq(&**self, &**other) }
835     #[inline]
836     fn ne(&self, other: &&'b str) -> bool { PartialEq::ne(&**self, &**other) }
837 }
838
839 #[stable(feature = "rust1", since = "1.0.0")]
840 impl<'a, 'b> PartialEq<Cow<'a, str>> for &'b str {
841     #[inline]
842     fn eq(&self, other: &Cow<'a, str>) -> bool { PartialEq::eq(&**self, &**other) }
843     #[inline]
844     fn ne(&self, other: &Cow<'a, str>) -> bool { PartialEq::ne(&**self, &**other) }
845 }
846
847 #[unstable(feature = "collections", reason = "waiting on Str stabilization")]
848 #[allow(deprecated)]
849 impl Str for String {
850     #[inline]
851     #[stable(feature = "rust1", since = "1.0.0")]
852     fn as_slice(&self) -> &str {
853         unsafe { mem::transmute(&*self.vec) }
854     }
855 }
856
857 #[stable(feature = "rust1", since = "1.0.0")]
858 impl Default for String {
859     #[inline]
860     #[stable(feature = "rust1", since = "1.0.0")]
861     fn default() -> String {
862         String::new()
863     }
864 }
865
866 #[stable(feature = "rust1", since = "1.0.0")]
867 impl fmt::Display for String {
868     #[inline]
869     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
870         fmt::Display::fmt(&**self, f)
871     }
872 }
873
874 #[stable(feature = "rust1", since = "1.0.0")]
875 impl fmt::Debug for String {
876     #[inline]
877     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
878         fmt::Debug::fmt(&**self, f)
879     }
880 }
881
882 #[stable(feature = "rust1", since = "1.0.0")]
883 impl hash::Hash for String {
884     #[inline]
885     fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
886         (**self).hash(hasher)
887     }
888 }
889
890 #[unstable(feature = "collections",
891            reason = "recent addition, needs more experience")]
892 impl<'a> Add<&'a str> for String {
893     type Output = String;
894
895     #[inline]
896     fn add(mut self, other: &str) -> String {
897         self.push_str(other);
898         self
899     }
900 }
901
902 #[stable(feature = "rust1", since = "1.0.0")]
903 impl ops::Index<ops::Range<usize>> for String {
904     type Output = str;
905
906     #[inline]
907     fn index(&self, index: ops::Range<usize>) -> &str {
908         &self[..][index]
909     }
910 }
911 #[stable(feature = "rust1", since = "1.0.0")]
912 impl ops::Index<ops::RangeTo<usize>> for String {
913     type Output = str;
914
915     #[inline]
916     fn index(&self, index: ops::RangeTo<usize>) -> &str {
917         &self[..][index]
918     }
919 }
920 #[stable(feature = "rust1", since = "1.0.0")]
921 impl ops::Index<ops::RangeFrom<usize>> for String {
922     type Output = str;
923
924     #[inline]
925     fn index(&self, index: ops::RangeFrom<usize>) -> &str {
926         &self[..][index]
927     }
928 }
929 #[stable(feature = "rust1", since = "1.0.0")]
930 impl ops::Index<ops::RangeFull> for String {
931     type Output = str;
932
933     #[inline]
934     fn index(&self, _index: ops::RangeFull) -> &str {
935         unsafe { mem::transmute(&*self.vec) }
936     }
937 }
938
939 #[stable(feature = "rust1", since = "1.0.0")]
940 impl ops::Deref for String {
941     type Target = str;
942
943     #[inline]
944     fn deref(&self) -> &str {
945         unsafe { mem::transmute(&self.vec[..]) }
946     }
947 }
948
949 /// Wrapper type providing a `&String` reference via `Deref`.
950 #[unstable(feature = "collections")]
951 pub struct DerefString<'a> {
952     x: DerefVec<'a, u8>
953 }
954
955 impl<'a> Deref for DerefString<'a> {
956     type Target = String;
957
958     #[inline]
959     fn deref<'b>(&'b self) -> &'b String {
960         unsafe { mem::transmute(&*self.x) }
961     }
962 }
963
964 /// Convert a string slice to a wrapper type providing a `&String` reference.
965 ///
966 /// # Examples
967 ///
968 /// ```
969 /// # #![feature(collections)]
970 /// use std::string::as_string;
971 ///
972 /// fn string_consumer(s: String) {
973 ///     assert_eq!(s, "foo".to_string());
974 /// }
975 ///
976 /// let string = as_string("foo").clone();
977 /// string_consumer(string);
978 /// ```
979 #[unstable(feature = "collections")]
980 pub fn as_string<'a>(x: &'a str) -> DerefString<'a> {
981     DerefString { x: as_vec(x.as_bytes()) }
982 }
983
984 #[unstable(feature = "collections", reason = "associated error type may change")]
985 impl FromStr for String {
986     type Err = ();
987     #[inline]
988     fn from_str(s: &str) -> Result<String, ()> {
989         Ok(String::from_str(s))
990     }
991 }
992
993 /// A generic trait for converting a value to a string
994 #[stable(feature = "rust1", since = "1.0.0")]
995 pub trait ToString {
996     /// Converts the value of `self` to an owned string
997     #[stable(feature = "rust1", since = "1.0.0")]
998     fn to_string(&self) -> String;
999 }
1000
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 impl<T: fmt::Display + ?Sized> ToString for T {
1003     #[inline]
1004     fn to_string(&self) -> String {
1005         use core::fmt::Write;
1006         let mut buf = String::new();
1007         let _ = buf.write_fmt(format_args!("{}", self));
1008         buf.shrink_to_fit();
1009         buf
1010     }
1011 }
1012
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 impl AsRef<str> for String {
1015     fn as_ref(&self) -> &str {
1016         self
1017     }
1018 }
1019
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 impl<'a> From<&'a str> for String {
1022     fn from(s: &'a str) -> String {
1023         s.to_string()
1024     }
1025 }
1026
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 impl Into<Vec<u8>> for String {
1029     fn into(self) -> Vec<u8> {
1030         self.into_bytes()
1031     }
1032 }
1033
1034 #[stable(feature = "rust1", since = "1.0.0")]
1035 impl IntoCow<'static, str> for String {
1036     #[inline]
1037     fn into_cow(self) -> Cow<'static, str> {
1038         Cow::Owned(self)
1039     }
1040 }
1041
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 impl<'a> IntoCow<'a, str> for &'a str {
1044     #[inline]
1045     fn into_cow(self) -> Cow<'a, str> {
1046         Cow::Borrowed(self)
1047     }
1048 }
1049
1050 #[allow(deprecated)]
1051 impl<'a> Str for Cow<'a, str> {
1052     #[inline]
1053     fn as_slice<'b>(&'b self) -> &'b str {
1054         &**self
1055     }
1056 }
1057
1058 /// A clone-on-write string
1059 #[deprecated(since = "1.0.0", reason = "use Cow<'a, str> instead")]
1060 #[stable(feature = "rust1", since = "1.0.0")]
1061 pub type CowString<'a> = Cow<'a, str>;
1062
1063 #[stable(feature = "rust1", since = "1.0.0")]
1064 impl fmt::Write for String {
1065     #[inline]
1066     fn write_str(&mut self, s: &str) -> fmt::Result {
1067         self.push_str(s);
1068         Ok(())
1069     }
1070 }