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