]> git.lizzy.rs Git - rust.git/blob - src/libcollections/string.rs
Stabilize `std::convert` and related code
[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     /// Extract a string slice containing the entire string.
368     #[inline]
369     #[unstable(feature = "convert",
370                reason = "waiting on RFC revision")]
371     pub fn as_str(&self) -> &str {
372         self
373     }
374
375     /// Pushes the given string onto this string buffer.
376     ///
377     /// # Examples
378     ///
379     /// ```
380     /// # #![feature(collections)]
381     /// let mut s = String::from_str("foo");
382     /// s.push_str("bar");
383     /// assert_eq!(s, "foobar");
384     /// ```
385     #[inline]
386     #[stable(feature = "rust1", since = "1.0.0")]
387     pub fn push_str(&mut self, string: &str) {
388         self.vec.push_all(string.as_bytes())
389     }
390
391     /// Returns the number of bytes that this string buffer can hold without
392     /// reallocating.
393     ///
394     /// # Examples
395     ///
396     /// ```
397     /// let s = String::with_capacity(10);
398     /// assert!(s.capacity() >= 10);
399     /// ```
400     #[inline]
401     #[stable(feature = "rust1", since = "1.0.0")]
402     pub fn capacity(&self) -> usize {
403         self.vec.capacity()
404     }
405
406     /// Reserves capacity for at least `additional` more bytes to be inserted
407     /// in the given `String`. The collection may reserve more space to avoid
408     /// frequent reallocations.
409     ///
410     /// # Panics
411     ///
412     /// Panics if the new capacity overflows `usize`.
413     ///
414     /// # Examples
415     ///
416     /// ```
417     /// let mut s = String::new();
418     /// s.reserve(10);
419     /// assert!(s.capacity() >= 10);
420     /// ```
421     #[inline]
422     #[stable(feature = "rust1", since = "1.0.0")]
423     pub fn reserve(&mut self, additional: usize) {
424         self.vec.reserve(additional)
425     }
426
427     /// Reserves the minimum capacity for exactly `additional` more bytes to be
428     /// inserted in the given `String`. Does nothing if the capacity is already
429     /// sufficient.
430     ///
431     /// Note that the allocator may give the collection more space than it
432     /// requests. Therefore capacity can not be relied upon to be precisely
433     /// minimal. Prefer `reserve` if future insertions are expected.
434     ///
435     /// # Panics
436     ///
437     /// Panics if the new capacity overflows `usize`.
438     ///
439     /// # Examples
440     ///
441     /// ```
442     /// let mut s = String::new();
443     /// s.reserve(10);
444     /// assert!(s.capacity() >= 10);
445     /// ```
446     #[inline]
447     #[stable(feature = "rust1", since = "1.0.0")]
448     pub fn reserve_exact(&mut self, additional: usize) {
449         self.vec.reserve_exact(additional)
450     }
451
452     /// Shrinks the capacity of this string buffer to match its length.
453     ///
454     /// # Examples
455     ///
456     /// ```
457     /// # #![feature(collections)]
458     /// let mut s = String::from_str("foo");
459     /// s.reserve(100);
460     /// assert!(s.capacity() >= 100);
461     /// s.shrink_to_fit();
462     /// assert_eq!(s.capacity(), 3);
463     /// ```
464     #[inline]
465     #[stable(feature = "rust1", since = "1.0.0")]
466     pub fn shrink_to_fit(&mut self) {
467         self.vec.shrink_to_fit()
468     }
469
470     /// Adds the given character to the end of the string.
471     ///
472     /// # Examples
473     ///
474     /// ```
475     /// # #![feature(collections)]
476     /// let mut s = String::from_str("abc");
477     /// s.push('1');
478     /// s.push('2');
479     /// s.push('3');
480     /// assert_eq!(s, "abc123");
481     /// ```
482     #[inline]
483     #[stable(feature = "rust1", since = "1.0.0")]
484     pub fn push(&mut self, ch: char) {
485         if (ch as u32) < 0x80 {
486             self.vec.push(ch as u8);
487             return;
488         }
489
490         let cur_len = self.len();
491         // This may use up to 4 bytes.
492         self.vec.reserve(4);
493
494         unsafe {
495             // Attempt to not use an intermediate buffer by just pushing bytes
496             // directly onto this string.
497             let slice = slice::from_raw_parts_mut (
498                 self.vec.as_mut_ptr().offset(cur_len as isize),
499                 4
500             );
501             let used = ch.encode_utf8(slice).unwrap_or(0);
502             self.vec.set_len(cur_len + used);
503         }
504     }
505
506     /// Works with the underlying buffer as a byte slice.
507     ///
508     /// # Examples
509     ///
510     /// ```
511     /// # #![feature(collections)]
512     /// let s = String::from_str("hello");
513     /// let b: &[_] = &[104, 101, 108, 108, 111];
514     /// assert_eq!(s.as_bytes(), b);
515     /// ```
516     #[inline]
517     #[stable(feature = "rust1", since = "1.0.0")]
518     pub fn as_bytes(&self) -> &[u8] {
519         &self.vec
520     }
521
522     /// Shortens a string to the specified length.
523     ///
524     /// # Panics
525     ///
526     /// Panics if `new_len` > current length,
527     /// or if `new_len` is not a character boundary.
528     ///
529     /// # Examples
530     ///
531     /// ```
532     /// # #![feature(collections)]
533     /// let mut s = String::from_str("hello");
534     /// s.truncate(2);
535     /// assert_eq!(s, "he");
536     /// ```
537     #[inline]
538     #[stable(feature = "rust1", since = "1.0.0")]
539     pub fn truncate(&mut self, new_len: usize) {
540         assert!(self.is_char_boundary(new_len));
541         self.vec.truncate(new_len)
542     }
543
544     /// Removes the last character from the string buffer and returns it.
545     /// Returns `None` if this string buffer is empty.
546     ///
547     /// # Examples
548     ///
549     /// ```
550     /// # #![feature(collections)]
551     /// let mut s = String::from_str("foo");
552     /// assert_eq!(s.pop(), Some('o'));
553     /// assert_eq!(s.pop(), Some('o'));
554     /// assert_eq!(s.pop(), Some('f'));
555     /// assert_eq!(s.pop(), None);
556     /// ```
557     #[inline]
558     #[stable(feature = "rust1", since = "1.0.0")]
559     pub fn pop(&mut self) -> Option<char> {
560         let len = self.len();
561         if len == 0 {
562             return None
563         }
564
565         let ch = self.char_at_reverse(len);
566         unsafe {
567             self.vec.set_len(len - ch.len_utf8());
568         }
569         Some(ch)
570     }
571
572     /// Removes the character from the string buffer at byte position `idx` and
573     /// returns it.
574     ///
575     /// # Warning
576     ///
577     /// This is an O(n) operation as it requires copying every element in the
578     /// buffer.
579     ///
580     /// # Panics
581     ///
582     /// If `idx` does not lie on a character boundary, or if it is out of
583     /// bounds, then this function will panic.
584     ///
585     /// # Examples
586     ///
587     /// ```
588     /// # #![feature(collections)]
589     /// let mut s = String::from_str("foo");
590     /// assert_eq!(s.remove(0), 'f');
591     /// assert_eq!(s.remove(1), 'o');
592     /// assert_eq!(s.remove(0), 'o');
593     /// ```
594     #[inline]
595     #[stable(feature = "rust1", since = "1.0.0")]
596     pub fn remove(&mut self, idx: usize) -> char {
597         let len = self.len();
598         assert!(idx <= len);
599
600         let ch = self.char_at(idx);
601         let next = idx + ch.len_utf8();
602         unsafe {
603             ptr::copy(self.vec.as_mut_ptr().offset(idx as isize),
604                       self.vec.as_ptr().offset(next as isize),
605                       len - next);
606             self.vec.set_len(len - (next - idx));
607         }
608         ch
609     }
610
611     /// Insert a character into the string buffer at byte position `idx`.
612     ///
613     /// # Warning
614     ///
615     /// This is an O(n) operation as it requires copying every element in the
616     /// buffer.
617     ///
618     /// # Panics
619     ///
620     /// If `idx` does not lie on a character boundary or is out of bounds, then
621     /// this function will panic.
622     #[inline]
623     #[stable(feature = "rust1", since = "1.0.0")]
624     pub fn insert(&mut self, idx: usize, ch: char) {
625         let len = self.len();
626         assert!(idx <= len);
627         assert!(self.is_char_boundary(idx));
628         self.vec.reserve(4);
629         let mut bits = [0; 4];
630         let amt = ch.encode_utf8(&mut bits).unwrap();
631
632         unsafe {
633             ptr::copy(self.vec.as_mut_ptr().offset((idx + amt) as isize),
634                       self.vec.as_ptr().offset(idx as isize),
635                       len - idx);
636             ptr::copy(self.vec.as_mut_ptr().offset(idx as isize),
637                       bits.as_ptr(),
638                       amt);
639             self.vec.set_len(len + amt);
640         }
641     }
642
643     /// Views the string buffer as a mutable sequence of bytes.
644     ///
645     /// This is unsafe because it does not check
646     /// to ensure that the resulting string will be valid UTF-8.
647     ///
648     /// # Examples
649     ///
650     /// ```
651     /// # #![feature(collections)]
652     /// let mut s = String::from_str("hello");
653     /// unsafe {
654     ///     let vec = s.as_mut_vec();
655     ///     assert!(vec == &[104, 101, 108, 108, 111]);
656     ///     vec.reverse();
657     /// }
658     /// assert_eq!(s, "olleh");
659     /// ```
660     #[inline]
661     #[stable(feature = "rust1", since = "1.0.0")]
662     pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
663         &mut self.vec
664     }
665
666     /// Return the number of bytes in this string.
667     ///
668     /// # Examples
669     ///
670     /// ```
671     /// let a = "foo".to_string();
672     /// assert_eq!(a.len(), 3);
673     /// ```
674     #[inline]
675     #[stable(feature = "rust1", since = "1.0.0")]
676     pub fn len(&self) -> usize { self.vec.len() }
677
678     /// Returns true if the string contains no bytes
679     ///
680     /// # Examples
681     ///
682     /// ```
683     /// let mut v = String::new();
684     /// assert!(v.is_empty());
685     /// v.push('a');
686     /// assert!(!v.is_empty());
687     /// ```
688     #[inline]
689     #[stable(feature = "rust1", since = "1.0.0")]
690     pub fn is_empty(&self) -> bool { self.len() == 0 }
691
692     /// Truncates the string, returning it to 0 length.
693     ///
694     /// # Examples
695     ///
696     /// ```
697     /// let mut s = "foo".to_string();
698     /// s.clear();
699     /// assert!(s.is_empty());
700     /// ```
701     #[inline]
702     #[stable(feature = "rust1", since = "1.0.0")]
703     pub fn clear(&mut self) {
704         self.vec.clear()
705     }
706 }
707
708 impl FromUtf8Error {
709     /// Consume this error, returning the bytes that were attempted to make a
710     /// `String` with.
711     #[stable(feature = "rust1", since = "1.0.0")]
712     pub fn into_bytes(self) -> Vec<u8> { self.bytes }
713
714     /// Access the underlying UTF8-error that was the cause of this error.
715     #[stable(feature = "rust1", since = "1.0.0")]
716     pub fn utf8_error(&self) -> Utf8Error { self.error }
717 }
718
719 #[stable(feature = "rust1", since = "1.0.0")]
720 impl fmt::Display for FromUtf8Error {
721     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
722         fmt::Display::fmt(&self.error, f)
723     }
724 }
725
726 #[stable(feature = "rust1", since = "1.0.0")]
727 impl Error for FromUtf8Error {
728     fn description(&self) -> &str { "invalid utf-8" }
729 }
730
731 #[stable(feature = "rust1", since = "1.0.0")]
732 impl fmt::Display for FromUtf16Error {
733     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
734         fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
735     }
736 }
737
738 #[stable(feature = "rust1", since = "1.0.0")]
739 impl Error for FromUtf16Error {
740     fn description(&self) -> &str { "invalid utf-16" }
741 }
742
743 #[stable(feature = "rust1", since = "1.0.0")]
744 impl FromIterator<char> for String {
745     fn from_iter<I: IntoIterator<Item=char>>(iter: I) -> String {
746         let mut buf = String::new();
747         buf.extend(iter);
748         buf
749     }
750 }
751
752 #[stable(feature = "rust1", since = "1.0.0")]
753 impl<'a> FromIterator<&'a str> for String {
754     fn from_iter<I: IntoIterator<Item=&'a str>>(iter: I) -> String {
755         let mut buf = String::new();
756         buf.extend(iter);
757         buf
758     }
759 }
760
761 #[unstable(feature = "collections",
762            reason = "waiting on Extend stabilization")]
763 impl Extend<char> for String {
764     fn extend<I: IntoIterator<Item=char>>(&mut self, iterable: I) {
765         let iterator = iterable.into_iter();
766         let (lower_bound, _) = iterator.size_hint();
767         self.reserve(lower_bound);
768         for ch in iterator {
769             self.push(ch)
770         }
771     }
772 }
773
774 #[unstable(feature = "collections",
775            reason = "waiting on Extend stabilization")]
776 impl<'a> Extend<&'a str> for String {
777     fn extend<I: IntoIterator<Item=&'a str>>(&mut self, iterable: I) {
778         let iterator = iterable.into_iter();
779         // A guess that at least one byte per iterator element will be needed.
780         let (lower_bound, _) = iterator.size_hint();
781         self.reserve(lower_bound);
782         for s in iterator {
783             self.push_str(s)
784         }
785     }
786 }
787
788 /// A convenience impl that delegates to the impl for `&str`
789 impl<'a, 'b> Pattern<'a> for &'b String {
790     type Searcher = <&'b str as Pattern<'a>>::Searcher;
791
792     fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
793         self[..].into_searcher(haystack)
794     }
795
796     #[inline]
797     fn is_contained_in(self, haystack: &'a str) -> bool {
798         self[..].is_contained_in(haystack)
799     }
800
801     #[inline]
802     fn is_prefix_of(self, haystack: &'a str) -> bool {
803         self[..].is_prefix_of(haystack)
804     }
805 }
806
807 #[stable(feature = "rust1", since = "1.0.0")]
808 impl PartialEq for String {
809     #[inline]
810     fn eq(&self, other: &String) -> bool { PartialEq::eq(&**self, &**other) }
811     #[inline]
812     fn ne(&self, other: &String) -> bool { PartialEq::ne(&**self, &**other) }
813 }
814
815 macro_rules! impl_eq {
816     ($lhs:ty, $rhs: ty) => {
817         #[stable(feature = "rust1", since = "1.0.0")]
818         impl<'a> PartialEq<$rhs> for $lhs {
819             #[inline]
820             fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
821             #[inline]
822             fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
823         }
824
825         #[stable(feature = "rust1", since = "1.0.0")]
826         impl<'a> PartialEq<$lhs> for $rhs {
827             #[inline]
828             fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) }
829             #[inline]
830             fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) }
831         }
832
833     }
834 }
835
836 impl_eq! { String, &'a str }
837 impl_eq! { Cow<'a, str>, String }
838
839 #[stable(feature = "rust1", since = "1.0.0")]
840 impl<'a, 'b> PartialEq<&'b str> for Cow<'a, str> {
841     #[inline]
842     fn eq(&self, other: &&'b str) -> bool { PartialEq::eq(&**self, &**other) }
843     #[inline]
844     fn ne(&self, other: &&'b str) -> bool { PartialEq::ne(&**self, &**other) }
845 }
846
847 #[stable(feature = "rust1", since = "1.0.0")]
848 impl<'a, 'b> PartialEq<Cow<'a, str>> for &'b str {
849     #[inline]
850     fn eq(&self, other: &Cow<'a, str>) -> bool { PartialEq::eq(&**self, &**other) }
851     #[inline]
852     fn ne(&self, other: &Cow<'a, str>) -> bool { PartialEq::ne(&**self, &**other) }
853 }
854
855 #[unstable(feature = "collections", reason = "waiting on Str stabilization")]
856 #[allow(deprecated)]
857 impl Str for String {
858     #[inline]
859     fn as_slice(&self) -> &str {
860         unsafe { mem::transmute(&*self.vec) }
861     }
862 }
863
864 #[stable(feature = "rust1", since = "1.0.0")]
865 impl Default for String {
866     #[inline]
867     #[stable(feature = "rust1", since = "1.0.0")]
868     fn default() -> String {
869         String::new()
870     }
871 }
872
873 #[stable(feature = "rust1", since = "1.0.0")]
874 impl fmt::Display for String {
875     #[inline]
876     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
877         fmt::Display::fmt(&**self, f)
878     }
879 }
880
881 #[stable(feature = "rust1", since = "1.0.0")]
882 impl fmt::Debug for String {
883     #[inline]
884     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
885         fmt::Debug::fmt(&**self, f)
886     }
887 }
888
889 #[stable(feature = "rust1", since = "1.0.0")]
890 impl hash::Hash for String {
891     #[inline]
892     fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
893         (**self).hash(hasher)
894     }
895 }
896
897 #[unstable(feature = "collections",
898            reason = "recent addition, needs more experience")]
899 impl<'a> Add<&'a str> for String {
900     type Output = String;
901
902     #[inline]
903     fn add(mut self, other: &str) -> String {
904         self.push_str(other);
905         self
906     }
907 }
908
909 #[stable(feature = "rust1", since = "1.0.0")]
910 impl ops::Index<ops::Range<usize>> for String {
911     type Output = str;
912
913     #[inline]
914     fn index(&self, index: ops::Range<usize>) -> &str {
915         &self[..][index]
916     }
917 }
918 #[stable(feature = "rust1", since = "1.0.0")]
919 impl ops::Index<ops::RangeTo<usize>> for String {
920     type Output = str;
921
922     #[inline]
923     fn index(&self, index: ops::RangeTo<usize>) -> &str {
924         &self[..][index]
925     }
926 }
927 #[stable(feature = "rust1", since = "1.0.0")]
928 impl ops::Index<ops::RangeFrom<usize>> for String {
929     type Output = str;
930
931     #[inline]
932     fn index(&self, index: ops::RangeFrom<usize>) -> &str {
933         &self[..][index]
934     }
935 }
936 #[stable(feature = "rust1", since = "1.0.0")]
937 impl ops::Index<ops::RangeFull> for String {
938     type Output = str;
939
940     #[inline]
941     fn index(&self, _index: ops::RangeFull) -> &str {
942         unsafe { mem::transmute(&*self.vec) }
943     }
944 }
945
946 #[stable(feature = "rust1", since = "1.0.0")]
947 impl ops::Deref for String {
948     type Target = str;
949
950     #[inline]
951     fn deref(&self) -> &str {
952         unsafe { mem::transmute(&self.vec[..]) }
953     }
954 }
955
956 /// Wrapper type providing a `&String` reference via `Deref`.
957 #[unstable(feature = "collections")]
958 pub struct DerefString<'a> {
959     x: DerefVec<'a, u8>
960 }
961
962 impl<'a> Deref for DerefString<'a> {
963     type Target = String;
964
965     #[inline]
966     fn deref<'b>(&'b self) -> &'b String {
967         unsafe { mem::transmute(&*self.x) }
968     }
969 }
970
971 /// Convert a string slice to a wrapper type providing a `&String` reference.
972 ///
973 /// # Examples
974 ///
975 /// ```
976 /// # #![feature(collections)]
977 /// use std::string::as_string;
978 ///
979 /// fn string_consumer(s: String) {
980 ///     assert_eq!(s, "foo".to_string());
981 /// }
982 ///
983 /// let string = as_string("foo").clone();
984 /// string_consumer(string);
985 /// ```
986 #[unstable(feature = "collections")]
987 pub fn as_string<'a>(x: &'a str) -> DerefString<'a> {
988     DerefString { x: as_vec(x.as_bytes()) }
989 }
990
991 #[unstable(feature = "collections", reason = "associated error type may change")]
992 impl FromStr for String {
993     type Err = ();
994     #[inline]
995     fn from_str(s: &str) -> Result<String, ()> {
996         Ok(String::from_str(s))
997     }
998 }
999
1000 /// A generic trait for converting a value to a string
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 pub trait ToString {
1003     /// Converts the value of `self` to an owned string
1004     #[stable(feature = "rust1", since = "1.0.0")]
1005     fn to_string(&self) -> String;
1006 }
1007
1008 #[stable(feature = "rust1", since = "1.0.0")]
1009 impl<T: fmt::Display + ?Sized> ToString for T {
1010     #[inline]
1011     fn to_string(&self) -> String {
1012         use core::fmt::Write;
1013         let mut buf = String::new();
1014         let _ = buf.write_fmt(format_args!("{}", self));
1015         buf.shrink_to_fit();
1016         buf
1017     }
1018 }
1019
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 impl AsRef<str> for String {
1022     fn as_ref(&self) -> &str {
1023         self
1024     }
1025 }
1026
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 impl<'a> From<&'a str> for String {
1029     fn from(s: &'a str) -> String {
1030         s.to_string()
1031     }
1032 }
1033
1034 #[stable(feature = "rust1", since = "1.0.0")]
1035 impl Into<Vec<u8>> for String {
1036     fn into(self) -> Vec<u8> {
1037         self.into_bytes()
1038     }
1039 }
1040
1041 #[stable(feature = "rust1", since = "1.0.0")]
1042 impl IntoCow<'static, str> for String {
1043     #[inline]
1044     fn into_cow(self) -> Cow<'static, str> {
1045         Cow::Owned(self)
1046     }
1047 }
1048
1049 #[stable(feature = "rust1", since = "1.0.0")]
1050 impl<'a> IntoCow<'a, str> for &'a str {
1051     #[inline]
1052     fn into_cow(self) -> Cow<'a, str> {
1053         Cow::Borrowed(self)
1054     }
1055 }
1056
1057 #[allow(deprecated)]
1058 impl<'a> Str for Cow<'a, str> {
1059     #[inline]
1060     fn as_slice<'b>(&'b self) -> &'b str {
1061         &**self
1062     }
1063 }
1064
1065 /// A clone-on-write string
1066 #[deprecated(since = "1.0.0", reason = "use Cow<'a, str> instead")]
1067 #[stable(feature = "rust1", since = "1.0.0")]
1068 pub type CowString<'a> = Cow<'a, str>;
1069
1070 #[stable(feature = "rust1", since = "1.0.0")]
1071 impl fmt::Write for String {
1072     #[inline]
1073     fn write_str(&mut self, s: &str) -> fmt::Result {
1074         self.push_str(s);
1075         Ok(())
1076     }
1077 }