]> git.lizzy.rs Git - rust.git/blob - src/libcollections/string.rs
Fix some broken and missing links in the docs
[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 //! A UTF-8 encoded, growable string.
12 //!
13 //! This module contains the [`String`] type, a trait for converting
14 //! [`ToString`]s, and several error types that may result from working with
15 //! [`String`]s.
16 //!
17 //! [`String`]: struct.String.html
18 //! [`ToString`]: trait.ToString.html
19
20 #![stable(feature = "rust1", since = "1.0.0")]
21
22 use core::fmt;
23 use core::hash;
24 use core::iter::FromIterator;
25 use core::mem;
26 use core::ops::{self, Add};
27 use core::ptr;
28 use core::slice;
29 use core::str::pattern::Pattern;
30 use rustc_unicode::char::{decode_utf16, REPLACEMENT_CHARACTER};
31 use rustc_unicode::str as unicode_str;
32
33 use borrow::{Cow, IntoCow};
34 use range::RangeArgument;
35 use str::{self, FromStr, Utf8Error, Chars};
36 use vec::Vec;
37 use boxed::Box;
38
39 /// A UTF-8 encoded, growable string.
40 ///
41 /// The `String` type is the most common string type that has ownership over the
42 /// contents of the string. It has a close relationship with its borrowed
43 /// counterpart, the primitive [`str`].
44 ///
45 /// [`str`]: ../primitive.str.html
46 ///
47 /// # Examples
48 ///
49 /// You can create a `String` from a literal string with `String::from`:
50 ///
51 /// ```
52 /// let hello = String::from("Hello, world!");
53 /// ```
54 ///
55 /// You can append a [`char`] to a `String` with the [`push()`] method, and
56 /// append a [`&str`] with the [`push_str()`] method:
57 ///
58 /// ```
59 /// let mut hello = String::from("Hello, ");
60 ///
61 /// hello.push('w');
62 /// hello.push_str("orld!");
63 /// ```
64 ///
65 /// [`char`]: ../primitive.char.html
66 /// [`push()`]: #method.push
67 /// [`push_str()`]: #method.push_str
68 ///
69 /// If you have a vector of UTF-8 bytes, you can create a `String` from it with
70 /// the [`from_utf8()`] method:
71 ///
72 /// ```
73 /// // some bytes, in a vector
74 /// let sparkle_heart = vec![240, 159, 146, 150];
75 ///
76 /// // We know these bytes are valid, so we'll use `unwrap()`.
77 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
78 ///
79 /// assert_eq!("💖", sparkle_heart);
80 /// ```
81 ///
82 /// [`from_utf8()`]: #method.from_utf8
83 ///
84 /// # UTF-8
85 ///
86 /// `String`s are always valid UTF-8. This has a few implications, the first of
87 /// which is that if you need a non-UTF-8 string, consider [`OsString`]. It is
88 /// similar, but without the UTF-8 constraint. The second implication is that
89 /// you cannot index into a `String`:
90 ///
91 /// ```ignore
92 /// let s = "hello";
93 ///
94 /// println!("The first letter of s is {}", s[0]); // ERROR!!!
95 /// ```
96 ///
97 /// [`OsString`]: ../ffi/struct.OsString.html
98 ///
99 /// Indexing is intended to be a constant-time operation, but UTF-8 encoding
100 /// does not allow us to do this. Furtheremore, it's not clear what sort of
101 /// thing the index should return: a byte, a codepoint, or a grapheme cluster.
102 /// The [`as_bytes()`] and [`chars()`] methods return iterators over the first
103 /// two, respectively.
104 ///
105 /// [`as_bytes()`]: #method.as_bytes
106 /// [`chars()`]: #method.chars
107 ///
108 /// # Deref
109 ///
110 /// `String`s implement [`Deref`]`<Target=str>`, and so inherit all of [`str`]'s
111 /// methods. In addition, this means that you can pass a `String` to any
112 /// function which takes a [`&str`] by using an ampersand (`&`):
113 ///
114 /// ```
115 /// fn takes_str(s: &str) { }
116 ///
117 /// let s = String::from("Hello");
118 ///
119 /// takes_str(&s);
120 /// ```
121 ///
122 /// [`&str`]: ../primitive.str.html
123 /// [`Deref`]: ../ops/trait.Deref.html
124 ///
125 /// This will create a [`&str`] from the `String` and pass it in. This
126 /// conversion is very inexpensive, and so generally, functions will accept
127 /// [`&str`]s as arguments unless they need a `String` for some specific reason.
128 ///
129 ///
130 /// # Representation
131 ///
132 /// A `String` is made up of three components: a pointer to some bytes, a
133 /// length, and a capacity. The pointer points to an internal buffer `String`
134 /// uses to store its data. The length is the number of bytes currently stored
135 /// in the buffer, and the capacity is the size of the buffer in bytes. As such,
136 /// the length will always be less than or equal to the capacity.
137 ///
138 /// This buffer is always stored on the heap.
139 ///
140 /// You can look at these with the [`as_ptr()`], [`len()`], and [`capacity()`]
141 /// methods:
142 ///
143 /// ```
144 /// use std::mem;
145 ///
146 /// let story = String::from("Once upon a time...");
147 ///
148 /// let ptr = story.as_ptr();
149 /// let len = story.len();
150 /// let capacity = story.capacity();
151 ///
152 /// // story has thirteen bytes
153 /// assert_eq!(19, len);
154 ///
155 /// // Now that we have our parts, we throw the story away.
156 /// mem::forget(story);
157 ///
158 /// // We can re-build a String out of ptr, len, and capacity. This is all
159 /// // unsafe becuase we are responsible for making sure the components are
160 /// // valid:
161 /// let s = unsafe { String::from_raw_parts(ptr as *mut _, len, capacity) } ;
162 ///
163 /// assert_eq!(String::from("Once upon a time..."), s);
164 /// ```
165 ///
166 /// [`as_ptr()`]: #method.as_ptr
167 /// [`len()`]: #method.len
168 /// [`capacity()`]: #method.capacity
169 ///
170 /// If a `String` has enough capacity, adding elements to it will not
171 /// re-allocate. For example, consider this program:
172 ///
173 /// ```
174 /// let mut s = String::new();
175 ///
176 /// println!("{}", s.capacity());
177 ///
178 /// for _ in 0..5 {
179 ///     s.push_str("hello");
180 ///     println!("{}", s.capacity());
181 /// }
182 /// ```
183 ///
184 /// This will output the following:
185 ///
186 /// ```text
187 /// 0
188 /// 5
189 /// 10
190 /// 20
191 /// 20
192 /// 40
193 /// ```
194 ///
195 /// At first, we have no memory allocated at all, but as we append to the
196 /// string, it increases its capacity appropriately. If we instead use the
197 /// [`with_capacity()`] method to allocate the correct capacity initially:
198 ///
199 /// ```
200 /// let mut s = String::with_capacity(25);
201 ///
202 /// println!("{}", s.capacity());
203 ///
204 /// for _ in 0..5 {
205 ///     s.push_str("hello");
206 ///     println!("{}", s.capacity());
207 /// }
208 /// ```
209 ///
210 /// [`with_capacity()`]: #method.with_capacity
211 ///
212 /// We end up with a different output:
213 ///
214 /// ```text
215 /// 25
216 /// 25
217 /// 25
218 /// 25
219 /// 25
220 /// 25
221 /// ```
222 ///
223 /// Here, there's no need to allocate more memory inside the loop.
224 #[derive(PartialOrd, Eq, Ord)]
225 #[stable(feature = "rust1", since = "1.0.0")]
226 pub struct String {
227     vec: Vec<u8>,
228 }
229
230 /// A possible error value when converting a `String` from a UTF-8 byte vector.
231 ///
232 /// This type is the error type for the [`from_utf8()`] method on [`String`]. It
233 /// is designed in such a way to carefully avoid reallocations: the
234 /// [`into_bytes()`] method will give back the byte vector that was used in the
235 /// conversion attempt.
236 ///
237 /// [`from_utf8()`]: struct.String.html#method.from_utf8
238 /// [`String`]: struct.String.html
239 /// [`into_bytes()`]: struct.FromUtf8Error.html#method.into_bytes
240 ///
241 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
242 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
243 /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
244 /// through the [`utf8_error()`] method.
245 ///
246 /// [`Utf8Error`]: ../str/struct.Utf8Error.html
247 /// [`std::str`]: ../str/index.html
248 /// [`u8`]: ../primitive.u8.html
249 /// [`&str`]: ../primitive.str.html
250 /// [`utf8_error()`]: #method.utf8_error
251 ///
252 /// # Examples
253 ///
254 /// Basic usage:
255 ///
256 /// ```
257 /// // some invalid bytes, in a vector
258 /// let bytes = vec![0, 159];
259 ///
260 /// let value = String::from_utf8(bytes);
261 ///
262 /// assert!(value.is_err());
263 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
264 /// ```
265 #[stable(feature = "rust1", since = "1.0.0")]
266 #[derive(Debug)]
267 pub struct FromUtf8Error {
268     bytes: Vec<u8>,
269     error: Utf8Error,
270 }
271
272 /// A possible error value when converting a `String` from a UTF-16 byte slice.
273 ///
274 /// This type is the error type for the [`from_utf16()`] method on [`String`].
275 ///
276 /// [`from_utf16()`]: struct.String.html#method.from_utf16
277 /// [`String`]: struct.String.html
278 ///
279 /// # Examples
280 ///
281 /// Basic usage:
282 ///
283 /// ```
284 /// // 𝄞mu<invalid>ic
285 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
286 ///           0xD800, 0x0069, 0x0063];
287 ///
288 /// assert!(String::from_utf16(v).is_err());
289 /// ```
290 #[stable(feature = "rust1", since = "1.0.0")]
291 #[derive(Debug)]
292 pub struct FromUtf16Error(());
293
294 impl String {
295     /// Creates a new empty `String`.
296     ///
297     /// Given that the `String` is empty, this will not allocate any initial
298     /// buffer. While that means that this initial operation is very
299     /// inexpensive, but may cause excessive allocation later, when you add
300     /// data. If you have an idea of how much data the `String` will hold,
301     /// consider the [`with_capacity()`] method to prevent excessive
302     /// re-allocation.
303     ///
304     /// [`with_capacity()`]: #method.with_capacity
305     ///
306     /// # Examples
307     ///
308     /// Basic usage:
309     ///
310     /// ```
311     /// let s = String::new();
312     /// ```
313     #[inline]
314     #[stable(feature = "rust1", since = "1.0.0")]
315     pub fn new() -> String {
316         String { vec: Vec::new() }
317     }
318
319     /// Creates a new empty `String` with a particular capacity.
320     ///
321     /// `String`s have an internal buffer to hold their data. The capacity is
322     /// the length of that buffer, and can be queried with the [`capacity()`]
323     /// method. This method creates an empty `String`, but one with an initial
324     /// buffer that can hold `capacity` bytes. This is useful when you may be
325     /// appending a bunch of data to the `String`, reducing the number of
326     /// reallocations it needs to do.
327     ///
328     /// [`capacity()`]: #method.capacity
329     ///
330     /// If the given capacity is `0`, no allocation will occur, and this method
331     /// is identical to the [`new()`] method.
332     ///
333     /// [`new()`]: #method.new
334     ///
335     /// # Examples
336     ///
337     /// Basic usage:
338     ///
339     /// ```
340     /// let mut s = String::with_capacity(10);
341     ///
342     /// // The String contains no chars, even though it has capacity for more
343     /// assert_eq!(s.len(), 0);
344     ///
345     /// // These are all done without reallocating...
346     /// let cap = s.capacity();
347     /// for i in 0..10 {
348     ///     s.push('a');
349     /// }
350     ///
351     /// assert_eq!(s.capacity(), cap);
352     ///
353     /// // ...but this may make the vector reallocate
354     /// s.push('a');
355     /// ```
356     #[inline]
357     #[stable(feature = "rust1", since = "1.0.0")]
358     pub fn with_capacity(capacity: usize) -> String {
359         String { vec: Vec::with_capacity(capacity) }
360     }
361
362     // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
363     // required for this method definition, is not available. Since we don't
364     // require this method for testing purposes, I'll just stub it
365     // NB see the slice::hack module in slice.rs for more information
366     #[inline]
367     #[cfg(test)]
368     pub fn from_str(_: &str) -> String {
369         panic!("not available with cfg(test)");
370     }
371
372     /// Converts a vector of bytes to a `String`.
373     ///
374     /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a vector of bytes
375     /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
376     /// two. Not all byte slices are valid `String`s, however: `String`
377     /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
378     /// the bytes are valid UTF-8, and then does the conversion.
379     ///
380     /// [`&str`]: ../primitive.str.html
381     /// [`u8`]: ../primitive.u8.html
382     /// [`Vec<u8>`]: ../vec/struct.Vec.html
383     ///
384     /// If you are sure that the byte slice is valid UTF-8, and you don't want
385     /// to incur the overhead of the validity check, there is an unsafe version
386     /// of this function, [`from_utf8_unchecked()`], which has the same behavior
387     /// but skips the check.
388     ///
389     /// [`from_utf8_unchecked()`]: struct.String.html#method.from_utf8_unchecked
390     ///
391     /// This method will take care to not copy the vector, for efficiency's
392     /// sake.
393     ///
394     /// If you need a `&str` instead of a `String`, consider
395     /// [`str::from_utf8()`].
396     ///
397     /// [`str::from_utf8()`]: ../str/fn.from_utf8.html
398     ///
399     /// # Failure
400     ///
401     /// Returns `Err` if the slice is not UTF-8 with a description as to why the
402     /// provided bytes are not UTF-8. The vector you moved in is also included.
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     /// // We know these bytes are valid, so we'll use `unwrap()`.
413     /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
414     ///
415     /// assert_eq!("💖", sparkle_heart);
416     /// ```
417     ///
418     /// Incorrect bytes:
419     ///
420     /// ```
421     /// // some invalid bytes, in a vector
422     /// let sparkle_heart = vec![0, 159, 146, 150];
423     ///
424     /// assert!(String::from_utf8(sparkle_heart).is_err());
425     /// ```
426     ///
427     /// See the docs for [`FromUtf8Error`] for more details on what you can do
428     /// with this error.
429     ///
430     /// [`FromUtf8Error`]: struct.FromUtf8Error.html
431     #[inline]
432     #[stable(feature = "rust1", since = "1.0.0")]
433     pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
434         match str::from_utf8(&vec) {
435             Ok(..) => Ok(String { vec: vec }),
436             Err(e) => {
437                 Err(FromUtf8Error {
438                     bytes: vec,
439                     error: e,
440                 })
441             }
442         }
443     }
444
445     /// Converts a slice of bytes to a `String`, including invalid characters.
446     ///
447     /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a slice of
448     /// bytes ([`&[u8]`][byteslice]) is made of bytes, so this function converts between
449     /// the two. Not all byte slices are valid string slices, however: [`&str`]
450     /// requires that it is valid UTF-8. During this conversion,
451     /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
452     /// `U+FFFD REPLACEMENT CHARACTER`, which looks like this: �
453     ///
454     /// [`&str`]: ../primitive.str.html
455     /// [`u8`]: ../primitive.u8.html
456     /// [byteslice]: ../primitive.slice.html
457     ///
458     /// If you are sure that the byte slice is valid UTF-8, and you don't want
459     /// to incur the overhead of the conversion, there is an unsafe version
460     /// of this function, [`from_utf8_unchecked()`], which has the same behavior
461     /// but skips the checks.
462     ///
463     /// [`from_utf8_unchecked()`]: struct.String.html#method.from_utf8_unchecked
464     ///
465     /// If you need a [`&str`] instead of a `String`, consider
466     /// [`str::from_utf8()`].
467     ///
468     /// [`str::from_utf8()`]: ../str/fn.from_utf8.html
469     ///
470     /// # Examples
471     ///
472     /// Basic usage:
473     ///
474     /// ```
475     /// // some bytes, in a vector
476     /// let sparkle_heart = vec![240, 159, 146, 150];
477     ///
478     /// // We know these bytes are valid, so we'll use `unwrap()`.
479     /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
480     ///
481     /// assert_eq!("💖", sparkle_heart);
482     /// ```
483     ///
484     /// Incorrect bytes:
485     ///
486     /// ```
487     /// // some invalid bytes
488     /// let input = b"Hello \xF0\x90\x80World";
489     /// let output = String::from_utf8_lossy(input);
490     ///
491     /// assert_eq!("Hello �World", output);
492     /// ```
493     #[stable(feature = "rust1", since = "1.0.0")]
494     pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
495         let mut i;
496         match str::from_utf8(v) {
497             Ok(s) => return Cow::Borrowed(s),
498             Err(e) => i = e.valid_up_to(),
499         }
500
501         const TAG_CONT_U8: u8 = 128;
502         const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
503         let total = v.len();
504         fn unsafe_get(xs: &[u8], i: usize) -> u8 {
505             unsafe { *xs.get_unchecked(i) }
506         }
507         fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 {
508             if i >= total {
509                 0
510             } else {
511                 unsafe_get(xs, i)
512             }
513         }
514
515         let mut res = String::with_capacity(total);
516
517         if i > 0 {
518             unsafe { res.as_mut_vec().extend_from_slice(&v[..i]) };
519         }
520
521         // subseqidx is the index of the first byte of the subsequence we're
522         // looking at.  It's used to copy a bunch of contiguous good codepoints
523         // at once instead of copying them one by one.
524         let mut subseqidx = i;
525
526         while i < total {
527             let i_ = i;
528             let byte = unsafe_get(v, i);
529             i += 1;
530
531             macro_rules! error { () => ({
532                 unsafe {
533                     if subseqidx != i_ {
534                         res.as_mut_vec().extend_from_slice(&v[subseqidx..i_]);
535                     }
536                     subseqidx = i;
537                     res.as_mut_vec().extend_from_slice(REPLACEMENT);
538                 }
539             })}
540
541             if byte < 128 {
542                 // subseqidx handles this
543             } else {
544                 let w = unicode_str::utf8_char_width(byte);
545
546                 match w {
547                     2 => {
548                         if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
549                             error!();
550                             continue;
551                         }
552                         i += 1;
553                     }
554                     3 => {
555                         match (byte, safe_get(v, i, total)) {
556                             (0xE0, 0xA0...0xBF) => (),
557                             (0xE1...0xEC, 0x80...0xBF) => (),
558                             (0xED, 0x80...0x9F) => (),
559                             (0xEE...0xEF, 0x80...0xBF) => (),
560                             _ => {
561                                 error!();
562                                 continue;
563                             }
564                         }
565                         i += 1;
566                         if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
567                             error!();
568                             continue;
569                         }
570                         i += 1;
571                     }
572                     4 => {
573                         match (byte, safe_get(v, i, total)) {
574                             (0xF0, 0x90...0xBF) => (),
575                             (0xF1...0xF3, 0x80...0xBF) => (),
576                             (0xF4, 0x80...0x8F) => (),
577                             _ => {
578                                 error!();
579                                 continue;
580                             }
581                         }
582                         i += 1;
583                         if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
584                             error!();
585                             continue;
586                         }
587                         i += 1;
588                         if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
589                             error!();
590                             continue;
591                         }
592                         i += 1;
593                     }
594                     _ => {
595                         error!();
596                         continue;
597                     }
598                 }
599             }
600         }
601         if subseqidx < total {
602             unsafe { res.as_mut_vec().extend_from_slice(&v[subseqidx..total]) };
603         }
604         Cow::Owned(res)
605     }
606
607     /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
608     /// if `v` contains any invalid data.
609     ///
610     /// # Examples
611     ///
612     /// Basic usage:
613     ///
614     /// ```
615     /// // 𝄞music
616     /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
617     ///           0x0073, 0x0069, 0x0063];
618     /// assert_eq!(String::from("𝄞music"),
619     ///            String::from_utf16(v).unwrap());
620     ///
621     /// // 𝄞mu<invalid>ic
622     /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
623     ///           0xD800, 0x0069, 0x0063];
624     /// assert!(String::from_utf16(v).is_err());
625     /// ```
626     #[stable(feature = "rust1", since = "1.0.0")]
627     pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
628         decode_utf16(v.iter().cloned()).collect::<Result<_, _>>().map_err(|_| FromUtf16Error(()))
629     }
630
631     /// Decode a UTF-16 encoded vector `v` into a string, replacing
632     /// invalid data with the replacement character (U+FFFD).
633     ///
634     /// # Examples
635     ///
636     /// Basic usage:
637     ///
638     /// ```
639     /// // 𝄞mus<invalid>ic<invalid>
640     /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
641     ///           0x0073, 0xDD1E, 0x0069, 0x0063,
642     ///           0xD834];
643     ///
644     /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
645     ///            String::from_utf16_lossy(v));
646     /// ```
647     #[inline]
648     #[stable(feature = "rust1", since = "1.0.0")]
649     pub fn from_utf16_lossy(v: &[u16]) -> String {
650         decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
651     }
652
653     /// Creates a new `String` from a length, capacity, and pointer.
654     ///
655     /// # Safety
656     ///
657     /// This is highly unsafe, due to the number of invariants that aren't
658     /// checked:
659     ///
660     /// * The memory at `ptr` needs to have been previously allocated by the
661     ///   same allocator the standard library uses.
662     /// * `length` needs to be less than or equal to `capacity`.
663     /// * `capacity` needs to be the correct value.
664     ///
665     /// Violating these may cause problems like corrupting the allocator's
666     /// internal datastructures.
667     ///
668     /// # Examples
669     ///
670     /// Basic usage:
671     ///
672     /// ```
673     /// use std::mem;
674     ///
675     /// unsafe {
676     ///     let s = String::from("hello");
677     ///     let ptr = s.as_ptr();
678     ///     let len = s.len();
679     ///     let capacity = s.capacity();
680     ///
681     ///     mem::forget(s);
682     ///
683     ///     let s = String::from_raw_parts(ptr as *mut _, len, capacity);
684     ///
685     ///     assert_eq!(String::from("hello"), s);
686     /// }
687     /// ```
688     #[inline]
689     #[stable(feature = "rust1", since = "1.0.0")]
690     pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
691         String { vec: Vec::from_raw_parts(buf, length, capacity) }
692     }
693
694     /// Converts a vector of bytes to a `String` without checking that the
695     /// string contains valid UTF-8.
696     ///
697     /// See the safe version, [`from_utf8()`], for more details.
698     ///
699     /// [`from_utf8()`]: struct.String.html#method.from_utf8
700     ///
701     /// # Safety
702     ///
703     /// This function is unsafe because it does not check that the bytes passed
704     /// to it are valid UTF-8. If this constraint is violated, it may cause
705     /// memory unsafety issues with future users of the `String`, as the rest of
706     /// the standard library assumes that `String`s are valid UTF-8.
707     ///
708     /// # Examples
709     ///
710     /// Basic usage:
711     ///
712     /// ```
713     /// // some bytes, in a vector
714     /// let sparkle_heart = vec![240, 159, 146, 150];
715     ///
716     /// let sparkle_heart = unsafe {
717     ///     String::from_utf8_unchecked(sparkle_heart)
718     /// };
719     ///
720     /// assert_eq!("💖", sparkle_heart);
721     /// ```
722     #[inline]
723     #[stable(feature = "rust1", since = "1.0.0")]
724     pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
725         String { vec: bytes }
726     }
727
728     /// Converts a `String` into a byte vector.
729     ///
730     /// This consumes the `String`, so we do not need to copy its contents.
731     ///
732     /// # Examples
733     ///
734     /// Basic usage:
735     ///
736     /// ```
737     /// let s = String::from("hello");
738     /// let bytes = s.into_bytes();
739     ///
740     /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
741     /// ```
742     #[inline]
743     #[stable(feature = "rust1", since = "1.0.0")]
744     pub fn into_bytes(self) -> Vec<u8> {
745         self.vec
746     }
747
748     /// Extracts a string slice containing the entire string.
749     #[inline]
750     #[unstable(feature = "convert",
751                reason = "waiting on RFC revision",
752                issue = "27729")]
753     pub fn as_str(&self) -> &str {
754         self
755     }
756
757     /// Appends a given string slice onto the end of this `String`.
758     ///
759     /// # Examples
760     ///
761     /// Basic usage:
762     ///
763     /// ```
764     /// let mut s = String::from("foo");
765     ///
766     /// s.push_str("bar");
767     ///
768     /// assert_eq!("foobar", s);
769     /// ```
770     #[inline]
771     #[stable(feature = "rust1", since = "1.0.0")]
772     pub fn push_str(&mut self, string: &str) {
773         self.vec.extend_from_slice(string.as_bytes())
774     }
775
776     /// Returns this `String`'s capacity, in bytes.
777     ///
778     /// # Examples
779     ///
780     /// Basic usage:
781     ///
782     /// ```
783     /// let s = String::with_capacity(10);
784     ///
785     /// assert!(s.capacity() >= 10);
786     /// ```
787     #[inline]
788     #[stable(feature = "rust1", since = "1.0.0")]
789     pub fn capacity(&self) -> usize {
790         self.vec.capacity()
791     }
792
793     /// Ensures that this `String`'s capacity is at least `additional` bytes
794     /// larger than its length.
795     ///
796     /// The capacity may be increased by more than `additional` bytes if it
797     /// chooses, to prevent frequent reallocations.
798     ///
799     /// If you do not want this "at least" behavior, see the [`reserve_exact()`]
800     /// method.
801     ///
802     /// [`reserve_exact()`]: #method.reserve_exact
803     ///
804     /// # Panics
805     ///
806     /// Panics if the new capacity overflows `usize`.
807     ///
808     /// # Examples
809     ///
810     /// Basic usage:
811     ///
812     /// ```
813     /// let mut s = String::new();
814     ///
815     /// s.reserve(10);
816     ///
817     /// assert!(s.capacity() >= 10);
818     /// ```
819     ///
820     /// This may not actually increase the capacity:
821     ///
822     /// ```
823     /// let mut s = String::with_capacity(10);
824     /// s.push('a');
825     /// s.push('b');
826     ///
827     /// // s now has a length of 2 and a capacity of 10
828     /// assert_eq!(2, s.len());
829     /// assert_eq!(10, s.capacity());
830     ///
831     /// // Since we already have an extra 8 capacity, calling this...
832     /// s.reserve(8);
833     ///
834     /// // ... doesn't actually increase.
835     /// assert_eq!(10, s.capacity());
836     /// ```
837     #[inline]
838     #[stable(feature = "rust1", since = "1.0.0")]
839     pub fn reserve(&mut self, additional: usize) {
840         self.vec.reserve(additional)
841     }
842
843     /// Ensures that this `String`'s capacity is `additional` bytes
844     /// larger than its length.
845     ///
846     /// Consider using the [`reserve()`] method unless you absolutely know
847     /// better than the allocator.
848     ///
849     /// [`reserve()`]: #method.reserve
850     ///
851     /// # Panics
852     ///
853     /// Panics if the new capacity overflows `usize`.
854     ///
855     /// # Examples
856     ///
857     /// Basic usage:
858     ///
859     /// ```
860     /// let mut s = String::new();
861     ///
862     /// s.reserve_exact(10);
863     ///
864     /// assert!(s.capacity() >= 10);
865     /// ```
866     ///
867     /// This may not actually increase the capacity:
868     ///
869     /// ```
870     /// let mut s = String::with_capacity(10);
871     /// s.push('a');
872     /// s.push('b');
873     ///
874     /// // s now has a length of 2 and a capacity of 10
875     /// assert_eq!(2, s.len());
876     /// assert_eq!(10, s.capacity());
877     ///
878     /// // Since we already have an extra 8 capacity, calling this...
879     /// s.reserve_exact(8);
880     ///
881     /// // ... doesn't actually increase.
882     /// assert_eq!(10, s.capacity());
883     /// ```
884     #[inline]
885     #[stable(feature = "rust1", since = "1.0.0")]
886     pub fn reserve_exact(&mut self, additional: usize) {
887         self.vec.reserve_exact(additional)
888     }
889
890     /// Shrinks the capacity of this `String` to match its length.
891     ///
892     /// # Examples
893     ///
894     /// Basic usage:
895     ///
896     /// ```
897     /// let mut s = String::from("foo");
898     ///
899     /// s.reserve(100);
900     /// assert!(s.capacity() >= 100);
901     ///
902     /// s.shrink_to_fit();
903     /// assert_eq!(3, s.capacity());
904     /// ```
905     #[inline]
906     #[stable(feature = "rust1", since = "1.0.0")]
907     pub fn shrink_to_fit(&mut self) {
908         self.vec.shrink_to_fit()
909     }
910
911     /// Appends the given `char` to the end of this `String`.
912     ///
913     /// # Examples
914     ///
915     /// Basic usage:
916     ///
917     /// ```
918     /// let mut s = String::from("abc");
919     ///
920     /// s.push('1');
921     /// s.push('2');
922     /// s.push('3');
923     ///
924     /// assert_eq!("abc123", s);
925     /// ```
926     #[inline]
927     #[stable(feature = "rust1", since = "1.0.0")]
928     pub fn push(&mut self, ch: char) {
929         match ch.len_utf8() {
930             1 => self.vec.push(ch as u8),
931             ch_len => {
932                 let cur_len = self.len();
933                 // This may use up to 4 bytes.
934                 self.vec.reserve(ch_len);
935
936                 unsafe {
937                     // Attempt to not use an intermediate buffer by just pushing bytes
938                     // directly onto this string.
939                     let slice = slice::from_raw_parts_mut(self.vec
940                                                               .as_mut_ptr()
941                                                               .offset(cur_len as isize),
942                                                           ch_len);
943                     let used = ch.encode_utf8(slice).unwrap_or(0);
944                     self.vec.set_len(cur_len + used);
945                 }
946             }
947         }
948     }
949
950     /// Returns a byte slice of this `String`'s contents.
951     ///
952     /// # Examples
953     ///
954     /// Basic usage:
955     ///
956     /// ```
957     /// let s = String::from("hello");
958     ///
959     /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
960     /// ```
961     #[inline]
962     #[stable(feature = "rust1", since = "1.0.0")]
963     pub fn as_bytes(&self) -> &[u8] {
964         &self.vec
965     }
966
967     /// Shortens this `String` to the specified length.
968     ///
969     /// # Panics
970     ///
971     /// Panics if `new_len` > current length, or if `new_len` does not lie on a
972     /// [`char`] boundary.
973     ///
974     /// [`char`]: ../primitive.char.html
975     ///
976     /// # Examples
977     ///
978     /// Basic usage:
979     ///
980     /// ```
981     /// let mut s = String::from("hello");
982     ///
983     /// s.truncate(2);
984     ///
985     /// assert_eq!("he", s);
986     /// ```
987     #[inline]
988     #[stable(feature = "rust1", since = "1.0.0")]
989     pub fn truncate(&mut self, new_len: usize) {
990         assert!(self.is_char_boundary(new_len));
991         self.vec.truncate(new_len)
992     }
993
994     /// Removes the last character from the string buffer and returns it.
995     ///
996     /// Returns `None` if this `String` is empty.
997     ///
998     /// # Examples
999     ///
1000     /// Basic usage:
1001     ///
1002     /// ```
1003     /// let mut s = String::from("foo");
1004     ///
1005     /// assert_eq!(s.pop(), Some('o'));
1006     /// assert_eq!(s.pop(), Some('o'));
1007     /// assert_eq!(s.pop(), Some('f'));
1008     ///
1009     /// assert_eq!(s.pop(), None);
1010     /// ```
1011     #[inline]
1012     #[stable(feature = "rust1", since = "1.0.0")]
1013     pub fn pop(&mut self) -> Option<char> {
1014         let len = self.len();
1015         if len == 0 {
1016             return None;
1017         }
1018
1019         let ch = self.char_at_reverse(len);
1020         unsafe {
1021             self.vec.set_len(len - ch.len_utf8());
1022         }
1023         Some(ch)
1024     }
1025
1026     /// Removes a `char` from this `String` at a byte position and returns it.
1027     ///
1028     /// This is an `O(n)` operation, as it requires copying every element in the
1029     /// buffer.
1030     ///
1031     /// # Panics
1032     ///
1033     /// Panics if `idx` is larger than or equal to the `String`'s length,
1034     /// or if it does not lie on a [`char`] boundary.
1035     ///
1036     /// [`char`]: ../primitive.char.html
1037     ///
1038     /// # Examples
1039     ///
1040     /// Basic usage:
1041     ///
1042     /// ```
1043     /// let mut s = String::from("foo");
1044     ///
1045     /// assert_eq!(s.remove(0), 'f');
1046     /// assert_eq!(s.remove(1), 'o');
1047     /// assert_eq!(s.remove(0), 'o');
1048     /// ```
1049     #[inline]
1050     #[stable(feature = "rust1", since = "1.0.0")]
1051     pub fn remove(&mut self, idx: usize) -> char {
1052         let len = self.len();
1053         assert!(idx < len);
1054
1055         let ch = self.char_at(idx);
1056         let next = idx + ch.len_utf8();
1057         unsafe {
1058             ptr::copy(self.vec.as_ptr().offset(next as isize),
1059                       self.vec.as_mut_ptr().offset(idx as isize),
1060                       len - next);
1061             self.vec.set_len(len - (next - idx));
1062         }
1063         ch
1064     }
1065
1066     /// Inserts a character into this `String` at a byte position.
1067     ///
1068     /// This is an `O(n)` operation as it requires copying every element in the
1069     /// buffer.
1070     ///
1071     /// # Panics
1072     ///
1073     /// Panics if `idx` is larger than the `String`'s length, or if it does not
1074     /// lie on a [`char`] boundary.
1075     ///
1076     /// [`char`]: ../primitive.char.html
1077     ///
1078     /// # Examples
1079     ///
1080     /// Basic usage:
1081     ///
1082     /// ```
1083     /// let mut s = String::with_capacity(3);
1084     ///
1085     /// s.insert(0, 'f');
1086     /// s.insert(1, 'o');
1087     /// s.insert(2, 'o');
1088     ///
1089     /// assert_eq!("foo", s);
1090     /// ```
1091     #[inline]
1092     #[stable(feature = "rust1", since = "1.0.0")]
1093     pub fn insert(&mut self, idx: usize, ch: char) {
1094         let len = self.len();
1095         assert!(idx <= len);
1096         assert!(self.is_char_boundary(idx));
1097         self.vec.reserve(4);
1098         let mut bits = [0; 4];
1099         let amt = ch.encode_utf8(&mut bits).unwrap();
1100
1101         unsafe {
1102             ptr::copy(self.vec.as_ptr().offset(idx as isize),
1103                       self.vec.as_mut_ptr().offset((idx + amt) as isize),
1104                       len - idx);
1105             ptr::copy(bits.as_ptr(),
1106                       self.vec.as_mut_ptr().offset(idx as isize),
1107                       amt);
1108             self.vec.set_len(len + amt);
1109         }
1110     }
1111
1112     /// Returns a mutable reference to the contents of this `String`.
1113     ///
1114     /// # Safety
1115     ///
1116     /// This function is unsafe because it does not check that the bytes passed
1117     /// to it are valid UTF-8. If this constraint is violated, it may cause
1118     /// memory unsafety issues with future users of the `String`, as the rest of
1119     /// the standard library assumes that `String`s are valid UTF-8.
1120     ///
1121     /// # Examples
1122     ///
1123     /// Basic usage:
1124     ///
1125     /// ```
1126     /// let mut s = String::from("hello");
1127     ///
1128     /// unsafe {
1129     ///     let vec = s.as_mut_vec();
1130     ///     assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1131     ///
1132     ///     vec.reverse();
1133     /// }
1134     /// assert_eq!(s, "olleh");
1135     /// ```
1136     #[inline]
1137     #[stable(feature = "rust1", since = "1.0.0")]
1138     pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1139         &mut self.vec
1140     }
1141
1142     /// Returns the length of this `String`, in bytes.
1143     ///
1144     /// # Examples
1145     ///
1146     /// Basic usage:
1147     ///
1148     /// ```
1149     /// let a = String::from("foo");
1150     ///
1151     /// assert_eq!(a.len(), 3);
1152     /// ```
1153     #[inline]
1154     #[stable(feature = "rust1", since = "1.0.0")]
1155     pub fn len(&self) -> usize {
1156         self.vec.len()
1157     }
1158
1159     /// Returns `true` if this `String` has a length of zero.
1160     ///
1161     /// Returns `false` otherwise.
1162     ///
1163     /// # Examples
1164     ///
1165     /// Basic usage:
1166     ///
1167     /// ```
1168     /// let mut v = String::new();
1169     /// assert!(v.is_empty());
1170     ///
1171     /// v.push('a');
1172     /// assert!(!v.is_empty());
1173     /// ```
1174     #[inline]
1175     #[stable(feature = "rust1", since = "1.0.0")]
1176     pub fn is_empty(&self) -> bool {
1177         self.len() == 0
1178     }
1179
1180     /// Truncates this `String`, removing all contents.
1181     ///
1182     /// While this means the `String` will have a length of zero, it does not
1183     /// touch its capacity.
1184     ///
1185     /// # Examples
1186     ///
1187     /// Basic usage:
1188     ///
1189     /// ```
1190     /// let mut s = String::from("foo");
1191     ///
1192     /// s.clear();
1193     ///
1194     /// assert!(s.is_empty());
1195     /// assert_eq!(0, s.len());
1196     /// assert_eq!(3, s.capacity());
1197     /// ```
1198     #[inline]
1199     #[stable(feature = "rust1", since = "1.0.0")]
1200     pub fn clear(&mut self) {
1201         self.vec.clear()
1202     }
1203
1204     /// Create a draining iterator that removes the specified range in the string
1205     /// and yields the removed chars.
1206     ///
1207     /// Note: The element range is removed even if the iterator is not
1208     /// consumed until the end.
1209     ///
1210     /// # Panics
1211     ///
1212     /// Panics if the starting point or end point do not lie on a [`char`]
1213     /// boundary, or if they're out of bounds.
1214     ///
1215     /// [`char`]: ../primitive.char.html
1216     ///
1217     /// # Examples
1218     ///
1219     /// Basic usage:
1220     ///
1221     /// ```
1222     /// let mut s = String::from("α is alpha, β is beta");
1223     /// let beta_offset = s.find('β').unwrap_or(s.len());
1224     ///
1225     /// // Remove the range up until the β from the string
1226     /// let t: String = s.drain(..beta_offset).collect();
1227     /// assert_eq!(t, "α is alpha, ");
1228     /// assert_eq!(s, "β is beta");
1229     ///
1230     /// // A full range clears the string
1231     /// s.drain(..);
1232     /// assert_eq!(s, "");
1233     /// ```
1234     #[stable(feature = "drain", since = "1.6.0")]
1235     pub fn drain<R>(&mut self, range: R) -> Drain
1236         where R: RangeArgument<usize>
1237     {
1238         // Memory safety
1239         //
1240         // The String version of Drain does not have the memory safety issues
1241         // of the vector version. The data is just plain bytes.
1242         // Because the range removal happens in Drop, if the Drain iterator is leaked,
1243         // the removal will not happen.
1244         let len = self.len();
1245         let start = *range.start().unwrap_or(&0);
1246         let end = *range.end().unwrap_or(&len);
1247
1248         // Take out two simultaneous borrows. The &mut String won't be accessed
1249         // until iteration is over, in Drop.
1250         let self_ptr = self as *mut _;
1251         // slicing does the appropriate bounds checks
1252         let chars_iter = self[start..end].chars();
1253
1254         Drain {
1255             start: start,
1256             end: end,
1257             iter: chars_iter,
1258             string: self_ptr,
1259         }
1260     }
1261
1262     /// Converts this `String` into a `Box<str>`.
1263     ///
1264     /// This will drop any excess capacity.
1265     ///
1266     /// # Examples
1267     ///
1268     /// Basic usage:
1269     ///
1270     /// ```
1271     /// let s = String::from("hello");
1272     ///
1273     /// let b = s.into_boxed_str();
1274     /// ```
1275     #[stable(feature = "box_str", since = "1.4.0")]
1276     pub fn into_boxed_str(self) -> Box<str> {
1277         let slice = self.vec.into_boxed_slice();
1278         unsafe { mem::transmute::<Box<[u8]>, Box<str>>(slice) }
1279     }
1280 }
1281
1282 impl FromUtf8Error {
1283     /// Returns the bytes that were attempted to convert to a `String`.
1284     ///
1285     /// This method is carefully constructed to avoid allocation. It will
1286     /// consume the error, moving out the bytes, so that a copy of the bytes
1287     /// does not need to be made.
1288     ///
1289     /// # Examples
1290     ///
1291     /// Basic usage:
1292     ///
1293     /// ```
1294     /// // some invalid bytes, in a vector
1295     /// let bytes = vec![0, 159];
1296     ///
1297     /// let value = String::from_utf8(bytes);
1298     ///
1299     /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1300     /// ```
1301     #[stable(feature = "rust1", since = "1.0.0")]
1302     pub fn into_bytes(self) -> Vec<u8> {
1303         self.bytes
1304     }
1305
1306     /// Fetch a `Utf8Error` to get more details about the conversion failure.
1307     ///
1308     /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1309     /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1310     /// an analogue to `FromUtf8Error`. See its documentation for more details
1311     /// on using it.
1312     ///
1313     /// [`Utf8Error`]: ../str/struct.Utf8Error.html
1314     /// [`std::str`]: ../str/index.html
1315     /// [`u8`]: ../primitive.u8.html
1316     /// [`&str`]: ../primitive.str.html
1317     ///
1318     /// # Examples
1319     ///
1320     /// Basic usage:
1321     ///
1322     /// ```
1323     /// // some invalid bytes, in a vector
1324     /// let bytes = vec![0, 159];
1325     ///
1326     /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1327     ///
1328     /// // the first byte is invalid here
1329     /// assert_eq!(1, error.valid_up_to());
1330     /// ```
1331     #[stable(feature = "rust1", since = "1.0.0")]
1332     pub fn utf8_error(&self) -> Utf8Error {
1333         self.error
1334     }
1335 }
1336
1337 #[stable(feature = "rust1", since = "1.0.0")]
1338 impl fmt::Display for FromUtf8Error {
1339     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1340         fmt::Display::fmt(&self.error, f)
1341     }
1342 }
1343
1344 #[stable(feature = "rust1", since = "1.0.0")]
1345 impl fmt::Display for FromUtf16Error {
1346     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1347         fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1348     }
1349 }
1350
1351 #[stable(feature = "rust1", since = "1.0.0")]
1352 impl Clone for String {
1353     fn clone(&self) -> Self {
1354         String { vec: self.vec.clone() }
1355     }
1356
1357     fn clone_from(&mut self, source: &Self) {
1358         self.vec.clone_from(&source.vec);
1359     }
1360 }
1361
1362 #[stable(feature = "rust1", since = "1.0.0")]
1363 impl FromIterator<char> for String {
1364     fn from_iter<I: IntoIterator<Item = char>>(iterable: I) -> String {
1365         let mut buf = String::new();
1366         buf.extend(iterable);
1367         buf
1368     }
1369 }
1370
1371 #[stable(feature = "rust1", since = "1.0.0")]
1372 impl<'a> FromIterator<&'a str> for String {
1373     fn from_iter<I: IntoIterator<Item = &'a str>>(iterable: I) -> String {
1374         let mut buf = String::new();
1375         buf.extend(iterable);
1376         buf
1377     }
1378 }
1379
1380 #[stable(feature = "extend_string", since = "1.4.0")]
1381 impl FromIterator<String> for String {
1382     fn from_iter<I: IntoIterator<Item = String>>(iterable: I) -> String {
1383         let mut buf = String::new();
1384         buf.extend(iterable);
1385         buf
1386     }
1387 }
1388
1389 #[stable(feature = "rust1", since = "1.0.0")]
1390 impl Extend<char> for String {
1391     fn extend<I: IntoIterator<Item = char>>(&mut self, iterable: I) {
1392         let iterator = iterable.into_iter();
1393         let (lower_bound, _) = iterator.size_hint();
1394         self.reserve(lower_bound);
1395         for ch in iterator {
1396             self.push(ch)
1397         }
1398     }
1399 }
1400
1401 #[stable(feature = "extend_ref", since = "1.2.0")]
1402 impl<'a> Extend<&'a char> for String {
1403     fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iterable: I) {
1404         self.extend(iterable.into_iter().cloned());
1405     }
1406 }
1407
1408 #[stable(feature = "rust1", since = "1.0.0")]
1409 impl<'a> Extend<&'a str> for String {
1410     fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iterable: I) {
1411         for s in iterable {
1412             self.push_str(s)
1413         }
1414     }
1415 }
1416
1417 #[stable(feature = "extend_string", since = "1.4.0")]
1418 impl Extend<String> for String {
1419     fn extend<I: IntoIterator<Item = String>>(&mut self, iterable: I) {
1420         for s in iterable {
1421             self.push_str(&s)
1422         }
1423     }
1424 }
1425
1426 /// A convenience impl that delegates to the impl for `&str`
1427 #[unstable(feature = "pattern",
1428            reason = "API not fully fleshed out and ready to be stabilized",
1429            issue = "27721")]
1430 impl<'a, 'b> Pattern<'a> for &'b String {
1431     type Searcher = <&'b str as Pattern<'a>>::Searcher;
1432
1433     fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1434         self[..].into_searcher(haystack)
1435     }
1436
1437     #[inline]
1438     fn is_contained_in(self, haystack: &'a str) -> bool {
1439         self[..].is_contained_in(haystack)
1440     }
1441
1442     #[inline]
1443     fn is_prefix_of(self, haystack: &'a str) -> bool {
1444         self[..].is_prefix_of(haystack)
1445     }
1446 }
1447
1448 #[stable(feature = "rust1", since = "1.0.0")]
1449 impl PartialEq for String {
1450     #[inline]
1451     fn eq(&self, other: &String) -> bool {
1452         PartialEq::eq(&self[..], &other[..])
1453     }
1454     #[inline]
1455     fn ne(&self, other: &String) -> bool {
1456         PartialEq::ne(&self[..], &other[..])
1457     }
1458 }
1459
1460 macro_rules! impl_eq {
1461     ($lhs:ty, $rhs: ty) => {
1462         #[stable(feature = "rust1", since = "1.0.0")]
1463         impl<'a, 'b> PartialEq<$rhs> for $lhs {
1464             #[inline]
1465             fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1466             #[inline]
1467             fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1468         }
1469
1470         #[stable(feature = "rust1", since = "1.0.0")]
1471         impl<'a, 'b> PartialEq<$lhs> for $rhs {
1472             #[inline]
1473             fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1474             #[inline]
1475             fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1476         }
1477
1478     }
1479 }
1480
1481 impl_eq! { String, str }
1482 impl_eq! { String, &'a str }
1483 impl_eq! { Cow<'a, str>, str }
1484 impl_eq! { Cow<'a, str>, &'b str }
1485 impl_eq! { Cow<'a, str>, String }
1486
1487 #[stable(feature = "rust1", since = "1.0.0")]
1488 impl Default for String {
1489     #[inline]
1490     fn default() -> String {
1491         String::new()
1492     }
1493 }
1494
1495 #[stable(feature = "rust1", since = "1.0.0")]
1496 impl fmt::Display for String {
1497     #[inline]
1498     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1499         fmt::Display::fmt(&**self, f)
1500     }
1501 }
1502
1503 #[stable(feature = "rust1", since = "1.0.0")]
1504 impl fmt::Debug for String {
1505     #[inline]
1506     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1507         fmt::Debug::fmt(&**self, f)
1508     }
1509 }
1510
1511 #[stable(feature = "rust1", since = "1.0.0")]
1512 impl hash::Hash for String {
1513     #[inline]
1514     fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1515         (**self).hash(hasher)
1516     }
1517 }
1518
1519 #[stable(feature = "rust1", since = "1.0.0")]
1520 impl<'a> Add<&'a str> for String {
1521     type Output = String;
1522
1523     #[inline]
1524     fn add(mut self, other: &str) -> String {
1525         self.push_str(other);
1526         self
1527     }
1528 }
1529
1530 #[stable(feature = "rust1", since = "1.0.0")]
1531 impl ops::Index<ops::Range<usize>> for String {
1532     type Output = str;
1533
1534     #[inline]
1535     fn index(&self, index: ops::Range<usize>) -> &str {
1536         &self[..][index]
1537     }
1538 }
1539 #[stable(feature = "rust1", since = "1.0.0")]
1540 impl ops::Index<ops::RangeTo<usize>> for String {
1541     type Output = str;
1542
1543     #[inline]
1544     fn index(&self, index: ops::RangeTo<usize>) -> &str {
1545         &self[..][index]
1546     }
1547 }
1548 #[stable(feature = "rust1", since = "1.0.0")]
1549 impl ops::Index<ops::RangeFrom<usize>> for String {
1550     type Output = str;
1551
1552     #[inline]
1553     fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1554         &self[..][index]
1555     }
1556 }
1557 #[stable(feature = "rust1", since = "1.0.0")]
1558 impl ops::Index<ops::RangeFull> for String {
1559     type Output = str;
1560
1561     #[inline]
1562     fn index(&self, _index: ops::RangeFull) -> &str {
1563         unsafe { str::from_utf8_unchecked(&self.vec) }
1564     }
1565 }
1566
1567 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1568 impl ops::IndexMut<ops::Range<usize>> for String {
1569     #[inline]
1570     fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1571         &mut self[..][index]
1572     }
1573 }
1574 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1575 impl ops::IndexMut<ops::RangeTo<usize>> for String {
1576     #[inline]
1577     fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1578         &mut self[..][index]
1579     }
1580 }
1581 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1582 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
1583     #[inline]
1584     fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1585         &mut self[..][index]
1586     }
1587 }
1588 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1589 impl ops::IndexMut<ops::RangeFull> for String {
1590     #[inline]
1591     fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1592         unsafe { mem::transmute(&mut *self.vec) }
1593     }
1594 }
1595
1596 #[stable(feature = "rust1", since = "1.0.0")]
1597 impl ops::Deref for String {
1598     type Target = str;
1599
1600     #[inline]
1601     fn deref(&self) -> &str {
1602         unsafe { str::from_utf8_unchecked(&self.vec) }
1603     }
1604 }
1605
1606 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1607 impl ops::DerefMut for String {
1608     #[inline]
1609     fn deref_mut(&mut self) -> &mut str {
1610         unsafe { mem::transmute(&mut *self.vec) }
1611     }
1612 }
1613
1614 /// An error when parsing a `String`.
1615 ///
1616 /// This `enum` is slightly awkward: it will never actually exist. This error is
1617 /// part of the type signature of the implementation of [`FromStr`] on
1618 /// [`String`]. The return type of [`from_str()`], requires that an error be
1619 /// defined, but, given that a [`String`] can always be made into a new
1620 /// [`String`] without error, this type will never actually be returned. As
1621 /// such, it is only here to satisfy said signature, and is useless otherwise.
1622 ///
1623 /// [`FromStr`]: ../str/trait.FromStr.html
1624 /// [`String`]: struct.String.html
1625 /// [`from_str()`]: ../str/trait.FromStr.html#tymethod.from_str
1626 #[stable(feature = "str_parse_error", since = "1.5.0")]
1627 #[derive(Copy)]
1628 pub enum ParseError {}
1629
1630 #[stable(feature = "rust1", since = "1.0.0")]
1631 impl FromStr for String {
1632     type Err = ParseError;
1633     #[inline]
1634     fn from_str(s: &str) -> Result<String, ParseError> {
1635         Ok(String::from(s))
1636     }
1637 }
1638
1639 #[stable(feature = "str_parse_error", since = "1.5.0")]
1640 impl Clone for ParseError {
1641     fn clone(&self) -> ParseError {
1642         match *self {}
1643     }
1644 }
1645
1646 #[stable(feature = "str_parse_error", since = "1.5.0")]
1647 impl fmt::Debug for ParseError {
1648     fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1649         match *self {}
1650     }
1651 }
1652
1653 #[stable(feature = "str_parse_error", since = "1.5.0")]
1654 impl PartialEq for ParseError {
1655     fn eq(&self, _: &ParseError) -> bool {
1656         match *self {}
1657     }
1658 }
1659
1660 #[stable(feature = "str_parse_error", since = "1.5.0")]
1661 impl Eq for ParseError {}
1662
1663 /// A trait for converting a value to a `String`.
1664 ///
1665 /// This trait is automatically implemented for any type which implements the
1666 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
1667 /// [`Display`] should be implemented instead, and you get the `ToString`
1668 /// implementation for free.
1669 ///
1670 /// [`Display`]: ../fmt/trait.Display.html
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 pub trait ToString {
1673     /// Converts the given value to a `String`.
1674     ///
1675     /// # Examples
1676     ///
1677     /// Basic usage:
1678     ///
1679     /// ```
1680     /// let i = 5;
1681     /// let five = String::from("5");
1682     ///
1683     /// assert_eq!(five, i.to_string());
1684     /// ```
1685     #[stable(feature = "rust1", since = "1.0.0")]
1686     fn to_string(&self) -> String;
1687 }
1688
1689 #[stable(feature = "rust1", since = "1.0.0")]
1690 impl<T: fmt::Display + ?Sized> ToString for T {
1691     #[inline]
1692     fn to_string(&self) -> String {
1693         use core::fmt::Write;
1694         let mut buf = String::new();
1695         let _ = buf.write_fmt(format_args!("{}", self));
1696         buf.shrink_to_fit();
1697         buf
1698     }
1699 }
1700
1701 #[stable(feature = "rust1", since = "1.0.0")]
1702 impl AsRef<str> for String {
1703     #[inline]
1704     fn as_ref(&self) -> &str {
1705         self
1706     }
1707 }
1708
1709 #[stable(feature = "rust1", since = "1.0.0")]
1710 impl AsRef<[u8]> for String {
1711     #[inline]
1712     fn as_ref(&self) -> &[u8] {
1713         self.as_bytes()
1714     }
1715 }
1716
1717 #[stable(feature = "rust1", since = "1.0.0")]
1718 impl<'a> From<&'a str> for String {
1719     #[cfg(not(test))]
1720     #[inline]
1721     fn from(s: &'a str) -> String {
1722         String { vec: <[_]>::to_vec(s.as_bytes()) }
1723     }
1724
1725     // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1726     // required for this method definition, is not available. Since we don't
1727     // require this method for testing purposes, I'll just stub it
1728     // NB see the slice::hack module in slice.rs for more information
1729     #[inline]
1730     #[cfg(test)]
1731     fn from(_: &str) -> String {
1732         panic!("not available with cfg(test)");
1733     }
1734 }
1735
1736 #[stable(feature = "rust1", since = "1.0.0")]
1737 impl<'a> From<&'a str> for Cow<'a, str> {
1738     #[inline]
1739     fn from(s: &'a str) -> Cow<'a, str> {
1740         Cow::Borrowed(s)
1741     }
1742 }
1743
1744 #[stable(feature = "rust1", since = "1.0.0")]
1745 impl<'a> From<String> for Cow<'a, str> {
1746     #[inline]
1747     fn from(s: String) -> Cow<'a, str> {
1748         Cow::Owned(s)
1749     }
1750 }
1751
1752 #[stable(feature = "rust1", since = "1.0.0")]
1753 impl Into<Vec<u8>> for String {
1754     fn into(self) -> Vec<u8> {
1755         self.into_bytes()
1756     }
1757 }
1758
1759 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`",
1760            issue= "27735")]
1761 impl IntoCow<'static, str> for String {
1762     #[inline]
1763     fn into_cow(self) -> Cow<'static, str> {
1764         Cow::Owned(self)
1765     }
1766 }
1767
1768 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`",
1769            issue = "27735")]
1770 impl<'a> IntoCow<'a, str> for &'a str {
1771     #[inline]
1772     fn into_cow(self) -> Cow<'a, str> {
1773         Cow::Borrowed(self)
1774     }
1775 }
1776
1777 #[stable(feature = "rust1", since = "1.0.0")]
1778 impl fmt::Write for String {
1779     #[inline]
1780     fn write_str(&mut self, s: &str) -> fmt::Result {
1781         self.push_str(s);
1782         Ok(())
1783     }
1784
1785     #[inline]
1786     fn write_char(&mut self, c: char) -> fmt::Result {
1787         self.push(c);
1788         Ok(())
1789     }
1790 }
1791
1792 /// A draining iterator for `String`.
1793 #[stable(feature = "drain", since = "1.6.0")]
1794 pub struct Drain<'a> {
1795     /// Will be used as &'a mut String in the destructor
1796     string: *mut String,
1797     /// Start of part to remove
1798     start: usize,
1799     /// End of part to remove
1800     end: usize,
1801     /// Current remaining range to remove
1802     iter: Chars<'a>,
1803 }
1804
1805 #[stable(feature = "drain", since = "1.6.0")]
1806 unsafe impl<'a> Sync for Drain<'a> {}
1807 #[stable(feature = "drain", since = "1.6.0")]
1808 unsafe impl<'a> Send for Drain<'a> {}
1809
1810 #[stable(feature = "drain", since = "1.6.0")]
1811 impl<'a> Drop for Drain<'a> {
1812     fn drop(&mut self) {
1813         unsafe {
1814             // Use Vec::drain. "Reaffirm" the bounds checks to avoid
1815             // panic code being inserted again.
1816             let self_vec = (*self.string).as_mut_vec();
1817             if self.start <= self.end && self.end <= self_vec.len() {
1818                 self_vec.drain(self.start..self.end);
1819             }
1820         }
1821     }
1822 }
1823
1824 #[stable(feature = "drain", since = "1.6.0")]
1825 impl<'a> Iterator for Drain<'a> {
1826     type Item = char;
1827
1828     #[inline]
1829     fn next(&mut self) -> Option<char> {
1830         self.iter.next()
1831     }
1832
1833     fn size_hint(&self) -> (usize, Option<usize>) {
1834         self.iter.size_hint()
1835     }
1836 }
1837
1838 #[stable(feature = "drain", since = "1.6.0")]
1839 impl<'a> DoubleEndedIterator for Drain<'a> {
1840     #[inline]
1841     fn next_back(&mut self) -> Option<char> {
1842         self.iter.next_back()
1843     }
1844 }