]> git.lizzy.rs Git - rust.git/blob - src/libcollections/string.rs
rustfmt libcollections
[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 //! An owned, growable string that enforces that its contents are valid UTF-8.
12
13 #![stable(feature = "rust1", since = "1.0.0")]
14
15 use core::fmt;
16 use core::hash;
17 use core::iter::FromIterator;
18 use core::mem;
19 use core::ops::{self, Deref, Add, Index};
20 use core::ptr;
21 use core::slice;
22 use core::str::pattern::Pattern;
23 use rustc_unicode::char::{decode_utf16, REPLACEMENT_CHARACTER};
24 use rustc_unicode::str as unicode_str;
25
26 use borrow::{Cow, IntoCow};
27 use range::RangeArgument;
28 use str::{self, FromStr, Utf8Error, Chars};
29 use vec::Vec;
30 use boxed::Box;
31
32 /// A growable string stored as a UTF-8 encoded buffer.
33 #[derive(PartialOrd, Eq, Ord)]
34 #[stable(feature = "rust1", since = "1.0.0")]
35 pub struct String {
36     vec: Vec<u8>,
37 }
38
39 /// A possible error value from the `String::from_utf8` function.
40 #[stable(feature = "rust1", since = "1.0.0")]
41 #[derive(Debug)]
42 pub struct FromUtf8Error {
43     bytes: Vec<u8>,
44     error: Utf8Error,
45 }
46
47 /// A possible error value from the `String::from_utf16` function.
48 #[stable(feature = "rust1", since = "1.0.0")]
49 #[derive(Debug)]
50 pub struct FromUtf16Error(());
51
52 impl String {
53     /// Creates a new string buffer initialized with the empty string.
54     ///
55     /// # Examples
56     ///
57     /// ```
58     /// # #![allow(unused_mut)]
59     /// let mut s = String::new();
60     /// ```
61     #[inline]
62     #[stable(feature = "rust1", since = "1.0.0")]
63     pub fn new() -> String {
64         String { vec: Vec::new() }
65     }
66
67     /// Creates a new string buffer with the given capacity.
68     /// The string will be able to hold exactly `capacity` bytes without
69     /// reallocating. If `capacity` is 0, the string will not allocate.
70     ///
71     /// # Examples
72     ///
73     /// ```
74     /// let mut s = String::with_capacity(10);
75     ///
76     /// // The String contains no chars, even though it has capacity for more
77     /// assert_eq!(s.len(), 0);
78     ///
79     /// // These are all done without reallocating...
80     /// let cap = s.capacity();
81     /// for i in 0..10 {
82     ///     s.push('a');
83     /// }
84     ///
85     /// assert_eq!(s.capacity(), cap);
86     ///
87     /// // ...but this may make the vector reallocate
88     /// s.push('a');
89     /// ```
90     #[inline]
91     #[stable(feature = "rust1", since = "1.0.0")]
92     pub fn with_capacity(capacity: usize) -> String {
93         String { vec: Vec::with_capacity(capacity) }
94     }
95
96     // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
97     // required for this method definition, is not available. Since we don't
98     // require this method for testing purposes, I'll just stub it
99     // NB see the slice::hack module in slice.rs for more information
100     #[inline]
101     #[cfg(test)]
102     pub fn from_str(_: &str) -> String {
103         panic!("not available with cfg(test)");
104     }
105
106     /// Converts a vector of bytes to a `String`.
107     ///
108     /// A string slice (`&str`) is made of bytes (`u8`), and a vector of bytes
109     /// (`Vec<u8>`) is made of bytes, so this function converts between the
110     /// two. Not all byte slices are valid `String`s, however: `String`
111     /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
112     /// the bytes are valid UTF-8, and then does the conversion.
113     ///
114     /// If you are sure that the byte slice is valid UTF-8, and you don't want
115     /// to incur the overhead of the validity check, there is an unsafe version
116     /// of this function, [`from_utf8_unchecked()`][fromutf8], which has the
117     /// same behavior but skips the check.
118     ///
119     /// [fromutf8]: struct.String.html#method.from_utf8_unchecked
120     ///
121     /// This method will take care to not copy the vector, for efficiency's
122     /// sake.
123     ///
124     /// If you need a `&str` instead of a `String`, consider
125     /// [`str::from_utf8()`][str].
126     ///
127     /// [str]: ../str/fn.from_utf8.html
128     ///
129     /// # Failure
130     ///
131     /// Returns `Err` if the slice is not UTF-8 with a description as to why the
132     /// provided bytes are not UTF-8. The vector you moved in is also included.
133     ///
134     /// # Examples
135     ///
136     /// Basic usage:
137     ///
138     /// ```
139     /// // some bytes, in a vector
140     /// let sparkle_heart = vec![240, 159, 146, 150];
141     ///
142     /// // We know these bytes are valid, so just use `unwrap()`.
143     /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
144     ///
145     /// assert_eq!("💖", sparkle_heart);
146     /// ```
147     ///
148     /// Incorrect bytes:
149     ///
150     /// ```
151     /// // some invalid bytes, in a vector
152     /// let sparkle_heart = vec![0, 159, 146, 150];
153     ///
154     /// assert!(String::from_utf8(sparkle_heart).is_err());
155     /// ```
156     ///
157     /// See the docs for [`FromUtf8Error`][error] for more details on what you
158     /// can do with this error.
159     ///
160     /// [error]: struct.FromUtf8Error.html
161     #[inline]
162     #[stable(feature = "rust1", since = "1.0.0")]
163     pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
164         match str::from_utf8(&vec) {
165             Ok(..) => Ok(String { vec: vec }),
166             Err(e) => {
167                 Err(FromUtf8Error {
168                     bytes: vec,
169                     error: e,
170                 })
171             }
172         }
173     }
174
175     /// Converts a slice of bytes to a `String`, including invalid characters.
176     ///
177     /// A string slice (`&str`) is made of bytes (`u8`), and a slice of bytes
178     /// (`&[u8]`) is made of bytes, so this function converts between the two.
179     /// Not all byte slices are valid string slices, however: `&str` requires
180     /// that it is valid UTF-8. During this conversion, `from_utf8_lossy()`
181     /// will replace any invalid UTF-8 sequences with
182     /// `U+FFFD REPLACEMENT CHARACTER`, which looks like this: �
183     ///
184     /// If you are sure that the byte slice is valid UTF-8, and you don't want
185     /// to incur the overhead of the conversion, there is an unsafe version
186     /// of this function, [`from_utf8_unchecked()`][fromutf8], which has the
187     /// same behavior but skips the checks.
188     ///
189     /// [fromutf8]: struct.String.html#method.from_utf8_unchecked
190     ///
191     /// If you need a `&str` instead of a `String`, consider
192     /// [`str::from_utf8()`][str].
193     ///
194     /// [str]: ../str/fn.from_utf8.html
195     ///
196     /// # Examples
197     ///
198     /// Basic usage:
199     ///
200     /// ```
201     /// // some bytes, in a vector
202     /// let sparkle_heart = vec![240, 159, 146, 150];
203     ///
204     /// // We know these bytes are valid, so just use `unwrap()`.
205     /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
206     ///
207     /// assert_eq!("💖", sparkle_heart);
208     /// ```
209     ///
210     /// Incorrect bytes:
211     ///
212     /// ```
213     /// // some invalid bytes
214     /// let input = b"Hello \xF0\x90\x80World";
215     /// let output = String::from_utf8_lossy(input);
216     ///
217     /// assert_eq!("Hello �World", output);
218     /// ```
219     #[stable(feature = "rust1", since = "1.0.0")]
220     pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
221         let mut i;
222         match str::from_utf8(v) {
223             Ok(s) => return Cow::Borrowed(s),
224             Err(e) => i = e.valid_up_to(),
225         }
226
227         const TAG_CONT_U8: u8 = 128;
228         const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
229         let total = v.len();
230         fn unsafe_get(xs: &[u8], i: usize) -> u8 {
231             unsafe { *xs.get_unchecked(i) }
232         }
233         fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 {
234             if i >= total {
235                 0
236             } else {
237                 unsafe_get(xs, i)
238             }
239         }
240
241         let mut res = String::with_capacity(total);
242
243         if i > 0 {
244             unsafe { res.as_mut_vec().push_all(&v[..i]) };
245         }
246
247         // subseqidx is the index of the first byte of the subsequence we're
248         // looking at.  It's used to copy a bunch of contiguous good codepoints
249         // at once instead of copying them one by one.
250         let mut subseqidx = i;
251
252         while i < total {
253             let i_ = i;
254             let byte = unsafe_get(v, i);
255             i += 1;
256
257             macro_rules! error { () => ({
258                 unsafe {
259                     if subseqidx != i_ {
260                         res.as_mut_vec().push_all(&v[subseqidx..i_]);
261                     }
262                     subseqidx = i;
263                     res.as_mut_vec().push_all(REPLACEMENT);
264                 }
265             })}
266
267             if byte < 128 {
268                 // subseqidx handles this
269             } else {
270                 let w = unicode_str::utf8_char_width(byte);
271
272                 match w {
273                     2 => {
274                         if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
275                             error!();
276                             continue;
277                         }
278                         i += 1;
279                     }
280                     3 => {
281                         match (byte, safe_get(v, i, total)) {
282                             (0xE0, 0xA0...0xBF) => (),
283                             (0xE1...0xEC, 0x80...0xBF) => (),
284                             (0xED, 0x80...0x9F) => (),
285                             (0xEE...0xEF, 0x80...0xBF) => (),
286                             _ => {
287                                 error!();
288                                 continue;
289                             }
290                         }
291                         i += 1;
292                         if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
293                             error!();
294                             continue;
295                         }
296                         i += 1;
297                     }
298                     4 => {
299                         match (byte, safe_get(v, i, total)) {
300                             (0xF0, 0x90...0xBF) => (),
301                             (0xF1...0xF3, 0x80...0xBF) => (),
302                             (0xF4, 0x80...0x8F) => (),
303                             _ => {
304                                 error!();
305                                 continue;
306                             }
307                         }
308                         i += 1;
309                         if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
310                             error!();
311                             continue;
312                         }
313                         i += 1;
314                         if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
315                             error!();
316                             continue;
317                         }
318                         i += 1;
319                     }
320                     _ => {
321                         error!();
322                         continue;
323                     }
324                 }
325             }
326         }
327         if subseqidx < total {
328             unsafe { res.as_mut_vec().push_all(&v[subseqidx..total]) };
329         }
330         Cow::Owned(res)
331     }
332
333     /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
334     /// if `v` contains any invalid data.
335     ///
336     /// # Examples
337     ///
338     /// ```
339     /// // 𝄞music
340     /// let mut v = &mut [0xD834, 0xDD1E, 0x006d, 0x0075,
341     ///                   0x0073, 0x0069, 0x0063];
342     /// assert_eq!(String::from_utf16(v).unwrap(),
343     ///            "𝄞music".to_string());
344     ///
345     /// // 𝄞mu<invalid>ic
346     /// v[4] = 0xD800;
347     /// assert!(String::from_utf16(v).is_err());
348     /// ```
349     #[stable(feature = "rust1", since = "1.0.0")]
350     pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
351         decode_utf16(v.iter().cloned()).collect::<Result<_, _>>().map_err(|_| FromUtf16Error(()))
352     }
353
354     /// Decode a UTF-16 encoded vector `v` into a string, replacing
355     /// invalid data with the replacement character (U+FFFD).
356     ///
357     /// # Examples
358     ///
359     /// ```
360     /// // 𝄞mus<invalid>ic<invalid>
361     /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
362     ///           0x0073, 0xDD1E, 0x0069, 0x0063,
363     ///           0xD834];
364     ///
365     /// assert_eq!(String::from_utf16_lossy(v),
366     ///            "𝄞mus\u{FFFD}ic\u{FFFD}".to_string());
367     /// ```
368     #[inline]
369     #[stable(feature = "rust1", since = "1.0.0")]
370     pub fn from_utf16_lossy(v: &[u16]) -> String {
371         decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
372     }
373
374     /// Creates a new `String` from a length, capacity, and pointer.
375     ///
376     /// # Safety
377     ///
378     /// This is _very_ unsafe because:
379     ///
380     /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`. Therefore, this
381     ///   function inherits all of its unsafety, see [its
382     ///   documentation](../vec/struct.Vec.html#method.from_raw_parts)
383     ///   for the invariants it expects, they also apply to this function.
384     /// * We assume that the `Vec` contains valid UTF-8.
385     #[inline]
386     #[stable(feature = "rust1", since = "1.0.0")]
387     pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
388         String { vec: Vec::from_raw_parts(buf, length, capacity) }
389     }
390
391     /// Converts a vector of bytes to a `String` without checking that the
392     /// string contains valid UTF-8.
393     ///
394     /// See the safe version, [`from_utf8()`][fromutf8], for more.
395     ///
396     /// [fromutf8]: struct.String.html#method.from_utf8
397     ///
398     /// # Safety
399     ///
400     /// This function is unsafe because it does not check that the bytes passed to
401     /// it are valid UTF-8. If this constraint is violated, undefined behavior
402     /// results, as the rest of Rust assumes that `String`s are valid UTF-8.
403     ///
404     /// # Examples
405     ///
406     /// Basic usage:
407     ///
408     /// ```
409     /// // some bytes, in a vector
410     /// let sparkle_heart = vec![240, 159, 146, 150];
411     ///
412     /// let sparkle_heart = unsafe {
413     ///     String::from_utf8_unchecked(sparkle_heart)
414     /// };
415     ///
416     /// assert_eq!("💖", sparkle_heart);
417     /// ```
418     #[inline]
419     #[stable(feature = "rust1", since = "1.0.0")]
420     pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
421         String { vec: bytes }
422     }
423
424     /// Returns the underlying byte buffer, encoded as UTF-8.
425     ///
426     /// # Examples
427     ///
428     /// ```
429     /// let s = String::from("hello");
430     /// let bytes = s.into_bytes();
431     /// assert_eq!(bytes, [104, 101, 108, 108, 111]);
432     /// ```
433     #[inline]
434     #[stable(feature = "rust1", since = "1.0.0")]
435     pub fn into_bytes(self) -> Vec<u8> {
436         self.vec
437     }
438
439     /// Extracts a string slice containing the entire string.
440     #[inline]
441     #[unstable(feature = "convert",
442                reason = "waiting on RFC revision",
443                issue = "27729")]
444     pub fn as_str(&self) -> &str {
445         self
446     }
447
448     /// Pushes the given string onto this string buffer.
449     ///
450     /// # Examples
451     ///
452     /// ```
453     /// let mut s = String::from("foo");
454     /// s.push_str("bar");
455     /// assert_eq!(s, "foobar");
456     /// ```
457     #[inline]
458     #[stable(feature = "rust1", since = "1.0.0")]
459     pub fn push_str(&mut self, string: &str) {
460         self.vec.push_all(string.as_bytes())
461     }
462
463     /// Returns the number of bytes that this string buffer can hold without
464     /// reallocating.
465     ///
466     /// # Examples
467     ///
468     /// ```
469     /// let s = String::with_capacity(10);
470     /// assert!(s.capacity() >= 10);
471     /// ```
472     #[inline]
473     #[stable(feature = "rust1", since = "1.0.0")]
474     pub fn capacity(&self) -> usize {
475         self.vec.capacity()
476     }
477
478     /// Reserves capacity for at least `additional` more bytes to be inserted
479     /// in the given `String`. The collection may reserve more space to avoid
480     /// frequent reallocations.
481     ///
482     /// # Panics
483     ///
484     /// Panics if the new capacity overflows `usize`.
485     ///
486     /// # Examples
487     ///
488     /// ```
489     /// let mut s = String::new();
490     /// s.reserve(10);
491     /// assert!(s.capacity() >= 10);
492     /// ```
493     #[inline]
494     #[stable(feature = "rust1", since = "1.0.0")]
495     pub fn reserve(&mut self, additional: usize) {
496         self.vec.reserve(additional)
497     }
498
499     /// Reserves the minimum capacity for exactly `additional` more bytes to be
500     /// inserted in the given `String`. Does nothing if the capacity is already
501     /// sufficient.
502     ///
503     /// Note that the allocator may give the collection more space than it
504     /// requests. Therefore capacity can not be relied upon to be precisely
505     /// minimal. Prefer `reserve` if future insertions are expected.
506     ///
507     /// # Panics
508     ///
509     /// Panics if the new capacity overflows `usize`.
510     ///
511     /// # Examples
512     ///
513     /// ```
514     /// let mut s = String::new();
515     /// s.reserve_exact(10);
516     /// assert!(s.capacity() >= 10);
517     /// ```
518     #[inline]
519     #[stable(feature = "rust1", since = "1.0.0")]
520     pub fn reserve_exact(&mut self, additional: usize) {
521         self.vec.reserve_exact(additional)
522     }
523
524     /// Shrinks the capacity of this string buffer to match its length.
525     ///
526     /// # Examples
527     ///
528     /// ```
529     /// let mut s = String::from("foo");
530     /// s.reserve(100);
531     /// assert!(s.capacity() >= 100);
532     /// s.shrink_to_fit();
533     /// assert_eq!(s.capacity(), 3);
534     /// ```
535     #[inline]
536     #[stable(feature = "rust1", since = "1.0.0")]
537     pub fn shrink_to_fit(&mut self) {
538         self.vec.shrink_to_fit()
539     }
540
541     /// Adds the given character to the end of the string.
542     ///
543     /// # Examples
544     ///
545     /// ```
546     /// let mut s = String::from("abc");
547     /// s.push('1');
548     /// s.push('2');
549     /// s.push('3');
550     /// assert_eq!(s, "abc123");
551     /// ```
552     #[inline]
553     #[stable(feature = "rust1", since = "1.0.0")]
554     pub fn push(&mut self, ch: char) {
555         match ch.len_utf8() {
556             1 => self.vec.push(ch as u8),
557             ch_len => {
558                 let cur_len = self.len();
559                 // This may use up to 4 bytes.
560                 self.vec.reserve(ch_len);
561
562                 unsafe {
563                     // Attempt to not use an intermediate buffer by just pushing bytes
564                     // directly onto this string.
565                     let slice = slice::from_raw_parts_mut(self.vec
566                                                               .as_mut_ptr()
567                                                               .offset(cur_len as isize),
568                                                           ch_len);
569                     let used = ch.encode_utf8(slice).unwrap_or(0);
570                     self.vec.set_len(cur_len + used);
571                 }
572             }
573         }
574     }
575
576     /// Works with the underlying buffer as a byte slice.
577     ///
578     /// # Examples
579     ///
580     /// ```
581     /// let s = String::from("hello");
582     /// assert_eq!(s.as_bytes(), [104, 101, 108, 108, 111]);
583     /// ```
584     #[inline]
585     #[stable(feature = "rust1", since = "1.0.0")]
586     pub fn as_bytes(&self) -> &[u8] {
587         &self.vec
588     }
589
590     /// Shortens a string to the specified length.
591     ///
592     /// # Panics
593     ///
594     /// Panics if `new_len` > current length,
595     /// or if `new_len` is not a character boundary.
596     ///
597     /// # Examples
598     ///
599     /// ```
600     /// let mut s = String::from("hello");
601     /// s.truncate(2);
602     /// assert_eq!(s, "he");
603     /// ```
604     #[inline]
605     #[stable(feature = "rust1", since = "1.0.0")]
606     pub fn truncate(&mut self, new_len: usize) {
607         assert!(self.is_char_boundary(new_len));
608         self.vec.truncate(new_len)
609     }
610
611     /// Removes the last character from the string buffer and returns it.
612     /// Returns `None` if this string buffer is empty.
613     ///
614     /// # Examples
615     ///
616     /// ```
617     /// let mut s = String::from("foo");
618     /// assert_eq!(s.pop(), Some('o'));
619     /// assert_eq!(s.pop(), Some('o'));
620     /// assert_eq!(s.pop(), Some('f'));
621     /// assert_eq!(s.pop(), None);
622     /// ```
623     #[inline]
624     #[stable(feature = "rust1", since = "1.0.0")]
625     pub fn pop(&mut self) -> Option<char> {
626         let len = self.len();
627         if len == 0 {
628             return None;
629         }
630
631         let ch = self.char_at_reverse(len);
632         unsafe {
633             self.vec.set_len(len - ch.len_utf8());
634         }
635         Some(ch)
636     }
637
638     /// Removes the character from the string buffer at byte position `idx` and
639     /// returns it.
640     ///
641     /// # Warning
642     ///
643     /// This is an O(n) operation as it requires copying every element in the
644     /// buffer.
645     ///
646     /// # Panics
647     ///
648     /// If `idx` does not lie on a character boundary, or if it is out of
649     /// bounds, then this function will panic.
650     ///
651     /// # Examples
652     ///
653     /// ```
654     /// let mut s = String::from("foo");
655     /// assert_eq!(s.remove(0), 'f');
656     /// assert_eq!(s.remove(1), 'o');
657     /// assert_eq!(s.remove(0), 'o');
658     /// ```
659     #[inline]
660     #[stable(feature = "rust1", since = "1.0.0")]
661     pub fn remove(&mut self, idx: usize) -> char {
662         let len = self.len();
663         assert!(idx <= len);
664
665         let ch = self.char_at(idx);
666         let next = idx + ch.len_utf8();
667         unsafe {
668             ptr::copy(self.vec.as_ptr().offset(next as isize),
669                       self.vec.as_mut_ptr().offset(idx as isize),
670                       len - next);
671             self.vec.set_len(len - (next - idx));
672         }
673         ch
674     }
675
676     /// Inserts a character into the string buffer at byte position `idx`.
677     ///
678     /// # Warning
679     ///
680     /// This is an O(n) operation as it requires copying every element in the
681     /// buffer.
682     ///
683     /// # Panics
684     ///
685     /// If `idx` does not lie on a character boundary or is out of bounds, then
686     /// this function will panic.
687     #[inline]
688     #[stable(feature = "rust1", since = "1.0.0")]
689     pub fn insert(&mut self, idx: usize, ch: char) {
690         let len = self.len();
691         assert!(idx <= len);
692         assert!(self.is_char_boundary(idx));
693         self.vec.reserve(4);
694         let mut bits = [0; 4];
695         let amt = ch.encode_utf8(&mut bits).unwrap();
696
697         unsafe {
698             ptr::copy(self.vec.as_ptr().offset(idx as isize),
699                       self.vec.as_mut_ptr().offset((idx + amt) as isize),
700                       len - idx);
701             ptr::copy(bits.as_ptr(),
702                       self.vec.as_mut_ptr().offset(idx as isize),
703                       amt);
704             self.vec.set_len(len + amt);
705         }
706     }
707
708     /// Views the string buffer as a mutable sequence of bytes.
709     ///
710     /// This is unsafe because it does not check
711     /// to ensure that the resulting string will be valid UTF-8.
712     ///
713     /// # Examples
714     ///
715     /// ```
716     /// let mut s = String::from("hello");
717     /// unsafe {
718     ///     let vec = s.as_mut_vec();
719     ///     assert!(vec == &[104, 101, 108, 108, 111]);
720     ///     vec.reverse();
721     /// }
722     /// assert_eq!(s, "olleh");
723     /// ```
724     #[inline]
725     #[stable(feature = "rust1", since = "1.0.0")]
726     pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
727         &mut self.vec
728     }
729
730     /// Returns the number of bytes in this string.
731     ///
732     /// # Examples
733     ///
734     /// ```
735     /// let a = "foo".to_string();
736     /// assert_eq!(a.len(), 3);
737     /// ```
738     #[inline]
739     #[stable(feature = "rust1", since = "1.0.0")]
740     pub fn len(&self) -> usize {
741         self.vec.len()
742     }
743
744     /// Returns true if the string contains no bytes
745     ///
746     /// # Examples
747     ///
748     /// ```
749     /// let mut v = String::new();
750     /// assert!(v.is_empty());
751     /// v.push('a');
752     /// assert!(!v.is_empty());
753     /// ```
754     #[inline]
755     #[stable(feature = "rust1", since = "1.0.0")]
756     pub fn is_empty(&self) -> bool {
757         self.len() == 0
758     }
759
760     /// Truncates the string, returning it to 0 length.
761     ///
762     /// # Examples
763     ///
764     /// ```
765     /// let mut s = "foo".to_string();
766     /// s.clear();
767     /// assert!(s.is_empty());
768     /// ```
769     #[inline]
770     #[stable(feature = "rust1", since = "1.0.0")]
771     pub fn clear(&mut self) {
772         self.vec.clear()
773     }
774
775     /// Create a draining iterator that removes the specified range in the string
776     /// and yields the removed chars from start to end. The element range is
777     /// removed even if the iterator is not consumed until the end.
778     ///
779     /// # Panics
780     ///
781     /// Panics if the starting point or end point are not on character boundaries,
782     /// or if they are out of bounds.
783     ///
784     /// # Examples
785     ///
786     /// ```
787     /// #![feature(drain)]
788     ///
789     /// let mut s = String::from("α is alpha, β is beta");
790     /// let beta_offset = s.find('β').unwrap_or(s.len());
791     ///
792     /// // Remove the range up until the β from the string
793     /// let t: String = s.drain(..beta_offset).collect();
794     /// assert_eq!(t, "α is alpha, ");
795     /// assert_eq!(s, "β is beta");
796     ///
797     /// // A full range clears the string
798     /// s.drain(..);
799     /// assert_eq!(s, "");
800     /// ```
801     #[unstable(feature = "drain",
802                reason = "recently added, matches RFC",
803                issue = "27711")]
804     pub fn drain<R>(&mut self, range: R) -> Drain
805         where R: RangeArgument<usize>
806     {
807         // Memory safety
808         //
809         // The String version of Drain does not have the memory safety issues
810         // of the vector version. The data is just plain bytes.
811         // Because the range removal happens in Drop, if the Drain iterator is leaked,
812         // the removal will not happen.
813         let len = self.len();
814         let start = *range.start().unwrap_or(&0);
815         let end = *range.end().unwrap_or(&len);
816
817         // Take out two simultaneous borrows. The &mut String won't be accessed
818         // until iteration is over, in Drop.
819         let self_ptr = self as *mut _;
820         // slicing does the appropriate bounds checks
821         let chars_iter = self[start..end].chars();
822
823         Drain {
824             start: start,
825             end: end,
826             iter: chars_iter,
827             string: self_ptr,
828         }
829     }
830
831     /// Converts the string into `Box<str>`.
832     ///
833     /// Note that this will drop any excess capacity.
834     #[stable(feature = "box_str", since = "1.4.0")]
835     pub fn into_boxed_str(self) -> Box<str> {
836         let slice = self.vec.into_boxed_slice();
837         unsafe { mem::transmute::<Box<[u8]>, Box<str>>(slice) }
838     }
839
840     /// Converts the string into `Box<str>`.
841     ///
842     /// Note that this will drop any excess capacity.
843     #[unstable(feature = "box_str2",
844                reason = "recently added, matches RFC",
845                issue = "27785")]
846     #[deprecated(since = "1.4.0", reason = "renamed to `into_boxed_str`")]
847     pub fn into_boxed_slice(self) -> Box<str> {
848         self.into_boxed_str()
849     }
850 }
851
852 impl FromUtf8Error {
853     /// Consumes this error, returning the bytes that were attempted to make a
854     /// `String` with.
855     #[stable(feature = "rust1", since = "1.0.0")]
856     pub fn into_bytes(self) -> Vec<u8> {
857         self.bytes
858     }
859
860     /// Access the underlying UTF8-error that was the cause of this error.
861     #[stable(feature = "rust1", since = "1.0.0")]
862     pub fn utf8_error(&self) -> Utf8Error {
863         self.error
864     }
865 }
866
867 #[stable(feature = "rust1", since = "1.0.0")]
868 impl fmt::Display for FromUtf8Error {
869     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
870         fmt::Display::fmt(&self.error, f)
871     }
872 }
873
874 #[stable(feature = "rust1", since = "1.0.0")]
875 impl fmt::Display for FromUtf16Error {
876     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
877         fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
878     }
879 }
880
881 #[stable(feature = "rust1", since = "1.0.0")]
882 impl Clone for String {
883     fn clone(&self) -> Self {
884         String { vec: self.vec.clone() }
885     }
886
887     fn clone_from(&mut self, source: &Self) {
888         self.vec.clone_from(&source.vec);
889     }
890 }
891
892 #[stable(feature = "rust1", since = "1.0.0")]
893 impl FromIterator<char> for String {
894     fn from_iter<I: IntoIterator<Item = char>>(iterable: I) -> String {
895         let mut buf = String::new();
896         buf.extend(iterable);
897         buf
898     }
899 }
900
901 #[stable(feature = "rust1", since = "1.0.0")]
902 impl<'a> FromIterator<&'a str> for String {
903     fn from_iter<I: IntoIterator<Item = &'a str>>(iterable: I) -> String {
904         let mut buf = String::new();
905         buf.extend(iterable);
906         buf
907     }
908 }
909
910 #[stable(feature = "extend_string", since = "1.4.0")]
911 impl FromIterator<String> for String {
912     fn from_iter<I: IntoIterator<Item = String>>(iterable: I) -> String {
913         let mut buf = String::new();
914         buf.extend(iterable);
915         buf
916     }
917 }
918
919 #[stable(feature = "rust1", since = "1.0.0")]
920 impl Extend<char> for String {
921     fn extend<I: IntoIterator<Item = char>>(&mut self, iterable: I) {
922         let iterator = iterable.into_iter();
923         let (lower_bound, _) = iterator.size_hint();
924         self.reserve(lower_bound);
925         for ch in iterator {
926             self.push(ch)
927         }
928     }
929 }
930
931 #[stable(feature = "extend_ref", since = "1.2.0")]
932 impl<'a> Extend<&'a char> for String {
933     fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iterable: I) {
934         self.extend(iterable.into_iter().cloned());
935     }
936 }
937
938 #[stable(feature = "rust1", since = "1.0.0")]
939 impl<'a> Extend<&'a str> for String {
940     fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iterable: I) {
941         for s in iterable {
942             self.push_str(s)
943         }
944     }
945 }
946
947 #[stable(feature = "extend_string", since = "1.4.0")]
948 impl Extend<String> for String {
949     fn extend<I: IntoIterator<Item = String>>(&mut self, iterable: I) {
950         for s in iterable {
951             self.push_str(&s)
952         }
953     }
954 }
955
956 /// A convenience impl that delegates to the impl for `&str`
957 #[unstable(feature = "pattern",
958            reason = "API not fully fleshed out and ready to be stabilized",
959            issue = "27721")]
960 impl<'a, 'b> Pattern<'a> for &'b String {
961     type Searcher = <&'b str as Pattern<'a>>::Searcher;
962
963     fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
964         self[..].into_searcher(haystack)
965     }
966
967     #[inline]
968     fn is_contained_in(self, haystack: &'a str) -> bool {
969         self[..].is_contained_in(haystack)
970     }
971
972     #[inline]
973     fn is_prefix_of(self, haystack: &'a str) -> bool {
974         self[..].is_prefix_of(haystack)
975     }
976 }
977
978 #[stable(feature = "rust1", since = "1.0.0")]
979 impl PartialEq for String {
980     #[inline]
981     fn eq(&self, other: &String) -> bool {
982         PartialEq::eq(&self[..], &other[..])
983     }
984     #[inline]
985     fn ne(&self, other: &String) -> bool {
986         PartialEq::ne(&self[..], &other[..])
987     }
988 }
989
990 macro_rules! impl_eq {
991     ($lhs:ty, $rhs: ty) => {
992         #[stable(feature = "rust1", since = "1.0.0")]
993         impl<'a, 'b> PartialEq<$rhs> for $lhs {
994             #[inline]
995             fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
996             #[inline]
997             fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
998         }
999
1000         #[stable(feature = "rust1", since = "1.0.0")]
1001         impl<'a, 'b> PartialEq<$lhs> for $rhs {
1002             #[inline]
1003             fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1004             #[inline]
1005             fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1006         }
1007
1008     }
1009 }
1010
1011 impl_eq! { String, str }
1012 impl_eq! { String, &'a str }
1013 impl_eq! { Cow<'a, str>, str }
1014 impl_eq! { Cow<'a, str>, &'b str }
1015 impl_eq! { Cow<'a, str>, String }
1016
1017 #[stable(feature = "rust1", since = "1.0.0")]
1018 impl Default for String {
1019     #[inline]
1020     fn default() -> String {
1021         String::new()
1022     }
1023 }
1024
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 impl fmt::Display for String {
1027     #[inline]
1028     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1029         fmt::Display::fmt(&**self, f)
1030     }
1031 }
1032
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 impl fmt::Debug for String {
1035     #[inline]
1036     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1037         fmt::Debug::fmt(&**self, f)
1038     }
1039 }
1040
1041 #[stable(feature = "rust1", since = "1.0.0")]
1042 impl hash::Hash for String {
1043     #[inline]
1044     fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1045         (**self).hash(hasher)
1046     }
1047 }
1048
1049 #[stable(feature = "rust1", since = "1.0.0")]
1050 impl<'a> Add<&'a str> for String {
1051     type Output = String;
1052
1053     #[inline]
1054     fn add(mut self, other: &str) -> String {
1055         self.push_str(other);
1056         self
1057     }
1058 }
1059
1060 #[stable(feature = "rust1", since = "1.0.0")]
1061 impl ops::Index<ops::Range<usize>> for String {
1062     type Output = str;
1063
1064     #[inline]
1065     fn index(&self, index: ops::Range<usize>) -> &str {
1066         &self[..][index]
1067     }
1068 }
1069 #[stable(feature = "rust1", since = "1.0.0")]
1070 impl ops::Index<ops::RangeTo<usize>> for String {
1071     type Output = str;
1072
1073     #[inline]
1074     fn index(&self, index: ops::RangeTo<usize>) -> &str {
1075         &self[..][index]
1076     }
1077 }
1078 #[stable(feature = "rust1", since = "1.0.0")]
1079 impl ops::Index<ops::RangeFrom<usize>> for String {
1080     type Output = str;
1081
1082     #[inline]
1083     fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1084         &self[..][index]
1085     }
1086 }
1087 #[stable(feature = "rust1", since = "1.0.0")]
1088 impl ops::Index<ops::RangeFull> for String {
1089     type Output = str;
1090
1091     #[inline]
1092     fn index(&self, _index: ops::RangeFull) -> &str {
1093         unsafe { str::from_utf8_unchecked(&self.vec) }
1094     }
1095 }
1096
1097 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1098 impl ops::IndexMut<ops::Range<usize>> for String {
1099     #[inline]
1100     fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1101         &mut self[..][index]
1102     }
1103 }
1104 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1105 impl ops::IndexMut<ops::RangeTo<usize>> for String {
1106     #[inline]
1107     fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1108         &mut self[..][index]
1109     }
1110 }
1111 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1112 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
1113     #[inline]
1114     fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1115         &mut self[..][index]
1116     }
1117 }
1118 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1119 impl ops::IndexMut<ops::RangeFull> for String {
1120     #[inline]
1121     fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1122         unsafe { mem::transmute(&mut *self.vec) }
1123     }
1124 }
1125
1126 #[stable(feature = "rust1", since = "1.0.0")]
1127 impl ops::Deref for String {
1128     type Target = str;
1129
1130     #[inline]
1131     fn deref(&self) -> &str {
1132         unsafe { str::from_utf8_unchecked(&self.vec) }
1133     }
1134 }
1135
1136 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1137 impl ops::DerefMut for String {
1138     #[inline]
1139     fn deref_mut(&mut self) -> &mut str {
1140         unsafe { mem::transmute(&mut *self.vec) }
1141     }
1142 }
1143
1144 /// Error returned from `String::from`
1145 #[stable(feature = "str_parse_error", since = "1.5.0")]
1146 #[derive(Copy)]
1147 pub enum ParseError {}
1148
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 impl FromStr for String {
1151     type Err = ParseError;
1152     #[inline]
1153     fn from_str(s: &str) -> Result<String, ParseError> {
1154         Ok(String::from(s))
1155     }
1156 }
1157
1158 #[stable(feature = "str_parse_error", since = "1.5.0")]
1159 impl Clone for ParseError {
1160     fn clone(&self) -> ParseError {
1161         match *self {}
1162     }
1163 }
1164
1165 #[stable(feature = "str_parse_error", since = "1.5.0")]
1166 impl fmt::Debug for ParseError {
1167     fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1168         match *self {}
1169     }
1170 }
1171
1172 #[stable(feature = "str_parse_error", since = "1.5.0")]
1173 impl PartialEq for ParseError {
1174     fn eq(&self, _: &ParseError) -> bool {
1175         match *self {}
1176     }
1177 }
1178
1179 #[stable(feature = "str_parse_error", since = "1.5.0")]
1180 impl Eq for ParseError {}
1181
1182 /// A generic trait for converting a value to a string
1183 #[stable(feature = "rust1", since = "1.0.0")]
1184 pub trait ToString {
1185     /// Converts the value of `self` to an owned string
1186     #[stable(feature = "rust1", since = "1.0.0")]
1187     fn to_string(&self) -> String;
1188 }
1189
1190 #[stable(feature = "rust1", since = "1.0.0")]
1191 impl<T: fmt::Display + ?Sized> ToString for T {
1192     #[inline]
1193     fn to_string(&self) -> String {
1194         use core::fmt::Write;
1195         let mut buf = String::new();
1196         let _ = buf.write_fmt(format_args!("{}", self));
1197         buf.shrink_to_fit();
1198         buf
1199     }
1200 }
1201
1202 #[stable(feature = "rust1", since = "1.0.0")]
1203 impl AsRef<str> for String {
1204     #[inline]
1205     fn as_ref(&self) -> &str {
1206         self
1207     }
1208 }
1209
1210 #[stable(feature = "rust1", since = "1.0.0")]
1211 impl AsRef<[u8]> for String {
1212     #[inline]
1213     fn as_ref(&self) -> &[u8] {
1214         self.as_bytes()
1215     }
1216 }
1217
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 impl<'a> From<&'a str> for String {
1220     #[cfg(not(test))]
1221     #[inline]
1222     fn from(s: &'a str) -> String {
1223         String { vec: <[_]>::to_vec(s.as_bytes()) }
1224     }
1225
1226     // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1227     // required for this method definition, is not available. Since we don't
1228     // require this method for testing purposes, I'll just stub it
1229     // NB see the slice::hack module in slice.rs for more information
1230     #[inline]
1231     #[cfg(test)]
1232     fn from(_: &str) -> String {
1233         panic!("not available with cfg(test)");
1234     }
1235 }
1236
1237 #[stable(feature = "rust1", since = "1.0.0")]
1238 impl<'a> From<&'a str> for Cow<'a, str> {
1239     #[inline]
1240     fn from(s: &'a str) -> Cow<'a, str> {
1241         Cow::Borrowed(s)
1242     }
1243 }
1244
1245 #[stable(feature = "rust1", since = "1.0.0")]
1246 impl<'a> From<String> for Cow<'a, str> {
1247     #[inline]
1248     fn from(s: String) -> Cow<'a, str> {
1249         Cow::Owned(s)
1250     }
1251 }
1252
1253 #[stable(feature = "rust1", since = "1.0.0")]
1254 impl Into<Vec<u8>> for String {
1255     fn into(self) -> Vec<u8> {
1256         self.into_bytes()
1257     }
1258 }
1259
1260 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`",
1261            issue= "27735")]
1262 impl IntoCow<'static, str> for String {
1263     #[inline]
1264     fn into_cow(self) -> Cow<'static, str> {
1265         Cow::Owned(self)
1266     }
1267 }
1268
1269 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`",
1270            issue = "27735")]
1271 impl<'a> IntoCow<'a, str> for &'a str {
1272     #[inline]
1273     fn into_cow(self) -> Cow<'a, str> {
1274         Cow::Borrowed(self)
1275     }
1276 }
1277
1278 #[stable(feature = "rust1", since = "1.0.0")]
1279 impl fmt::Write for String {
1280     #[inline]
1281     fn write_str(&mut self, s: &str) -> fmt::Result {
1282         self.push_str(s);
1283         Ok(())
1284     }
1285
1286     #[inline]
1287     fn write_char(&mut self, c: char) -> fmt::Result {
1288         self.push(c);
1289         Ok(())
1290     }
1291 }
1292
1293 /// A draining iterator for `String`.
1294 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1295 pub struct Drain<'a> {
1296     /// Will be used as &'a mut String in the destructor
1297     string: *mut String,
1298     /// Start of part to remove
1299     start: usize,
1300     /// End of part to remove
1301     end: usize,
1302     /// Current remaining range to remove
1303     iter: Chars<'a>,
1304 }
1305
1306 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1307 unsafe impl<'a> Sync for Drain<'a> {}
1308 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1309 unsafe impl<'a> Send for Drain<'a> {}
1310
1311 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1312 impl<'a> Drop for Drain<'a> {
1313     fn drop(&mut self) {
1314         unsafe {
1315             // Use Vec::drain. "Reaffirm" the bounds checks to avoid
1316             // panic code being inserted again.
1317             let self_vec = (*self.string).as_mut_vec();
1318             if self.start <= self.end && self.end <= self_vec.len() {
1319                 self_vec.drain(self.start..self.end);
1320             }
1321         }
1322     }
1323 }
1324
1325 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1326 impl<'a> Iterator for Drain<'a> {
1327     type Item = char;
1328
1329     #[inline]
1330     fn next(&mut self) -> Option<char> {
1331         self.iter.next()
1332     }
1333
1334     fn size_hint(&self) -> (usize, Option<usize>) {
1335         self.iter.size_hint()
1336     }
1337 }
1338
1339 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1340 impl<'a> DoubleEndedIterator for Drain<'a> {
1341     #[inline]
1342     fn next_back(&mut self) -> Option<char> {
1343         self.iter.next_back()
1344     }
1345 }