]> git.lizzy.rs Git - rust.git/blob - src/libcollections/string.rs
d2cbcad875f347a5249f547829ca463c424bb431
[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 or equal to the `String`'s length,
1033     /// or if it does not 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.
1205     ///
1206     /// Note: The element range is removed even if the iterator is not
1207     /// consumed until the end.
1208     ///
1209     /// # Panics
1210     ///
1211     /// Panics if the starting point or end point do not lie on a [`char`]
1212     /// boundary, or if they're out of bounds.
1213     ///
1214     /// [`char`]: ../primitive.char.html
1215     ///
1216     /// # Examples
1217     ///
1218     /// Basic usage:
1219     ///
1220     /// ```
1221     /// let mut s = String::from("α is alpha, β is beta");
1222     /// let beta_offset = s.find('β').unwrap_or(s.len());
1223     ///
1224     /// // Remove the range up until the β from the string
1225     /// let t: String = s.drain(..beta_offset).collect();
1226     /// assert_eq!(t, "α is alpha, ");
1227     /// assert_eq!(s, "β is beta");
1228     ///
1229     /// // A full range clears the string
1230     /// s.drain(..);
1231     /// assert_eq!(s, "");
1232     /// ```
1233     #[stable(feature = "drain", since = "1.6.0")]
1234     pub fn drain<R>(&mut self, range: R) -> Drain
1235         where R: RangeArgument<usize>
1236     {
1237         // Memory safety
1238         //
1239         // The String version of Drain does not have the memory safety issues
1240         // of the vector version. The data is just plain bytes.
1241         // Because the range removal happens in Drop, if the Drain iterator is leaked,
1242         // the removal will not happen.
1243         let len = self.len();
1244         let start = *range.start().unwrap_or(&0);
1245         let end = *range.end().unwrap_or(&len);
1246
1247         // Take out two simultaneous borrows. The &mut String won't be accessed
1248         // until iteration is over, in Drop.
1249         let self_ptr = self as *mut _;
1250         // slicing does the appropriate bounds checks
1251         let chars_iter = self[start..end].chars();
1252
1253         Drain {
1254             start: start,
1255             end: end,
1256             iter: chars_iter,
1257             string: self_ptr,
1258         }
1259     }
1260
1261     /// Converts this `String` into a `Box<str>`.
1262     ///
1263     /// This will drop any excess capacity.
1264     ///
1265     /// # Examples
1266     ///
1267     /// Basic usage:
1268     ///
1269     /// ```
1270     /// let s = String::from("hello");
1271     ///
1272     /// let b = s.into_boxed_str();
1273     /// ```
1274     #[stable(feature = "box_str", since = "1.4.0")]
1275     pub fn into_boxed_str(self) -> Box<str> {
1276         let slice = self.vec.into_boxed_slice();
1277         unsafe { mem::transmute::<Box<[u8]>, Box<str>>(slice) }
1278     }
1279 }
1280
1281 impl FromUtf8Error {
1282     /// Returns the bytes that were attempted to convert to a `String`.
1283     ///
1284     /// This method is carefully constructed to avoid allocation. It will
1285     /// consume the error, moving out the bytes, so that a copy of the bytes
1286     /// does not need to be made.
1287     ///
1288     /// # Examples
1289     ///
1290     /// Basic usage:
1291     ///
1292     /// ```
1293     /// // some invalid bytes, in a vector
1294     /// let bytes = vec![0, 159];
1295     ///
1296     /// let value = String::from_utf8(bytes);
1297     ///
1298     /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1299     /// ```
1300     #[stable(feature = "rust1", since = "1.0.0")]
1301     pub fn into_bytes(self) -> Vec<u8> {
1302         self.bytes
1303     }
1304
1305     /// Fetch a `Utf8Error` to get more details about the conversion failure.
1306     ///
1307     /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1308     /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1309     /// an analogue to `FromUtf8Error`. See its documentation for more details
1310     /// on using it.
1311     ///
1312     /// [`Utf8Error`]: ../str/struct.Utf8Error.html
1313     /// [`std::str`]: ../str/index.html
1314     ///
1315     /// # Examples
1316     ///
1317     /// Basic usage:
1318     ///
1319     /// ```
1320     /// // some invalid bytes, in a vector
1321     /// let bytes = vec![0, 159];
1322     ///
1323     /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1324     ///
1325     /// // the first byte is invalid here
1326     /// assert_eq!(1, error.valid_up_to());
1327     /// ```
1328     #[stable(feature = "rust1", since = "1.0.0")]
1329     pub fn utf8_error(&self) -> Utf8Error {
1330         self.error
1331     }
1332 }
1333
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 impl fmt::Display for FromUtf8Error {
1336     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1337         fmt::Display::fmt(&self.error, f)
1338     }
1339 }
1340
1341 #[stable(feature = "rust1", since = "1.0.0")]
1342 impl fmt::Display for FromUtf16Error {
1343     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1344         fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1345     }
1346 }
1347
1348 #[stable(feature = "rust1", since = "1.0.0")]
1349 impl Clone for String {
1350     fn clone(&self) -> Self {
1351         String { vec: self.vec.clone() }
1352     }
1353
1354     fn clone_from(&mut self, source: &Self) {
1355         self.vec.clone_from(&source.vec);
1356     }
1357 }
1358
1359 #[stable(feature = "rust1", since = "1.0.0")]
1360 impl FromIterator<char> for String {
1361     fn from_iter<I: IntoIterator<Item = char>>(iterable: I) -> String {
1362         let mut buf = String::new();
1363         buf.extend(iterable);
1364         buf
1365     }
1366 }
1367
1368 #[stable(feature = "rust1", since = "1.0.0")]
1369 impl<'a> FromIterator<&'a str> for String {
1370     fn from_iter<I: IntoIterator<Item = &'a str>>(iterable: I) -> String {
1371         let mut buf = String::new();
1372         buf.extend(iterable);
1373         buf
1374     }
1375 }
1376
1377 #[stable(feature = "extend_string", since = "1.4.0")]
1378 impl FromIterator<String> for String {
1379     fn from_iter<I: IntoIterator<Item = String>>(iterable: I) -> String {
1380         let mut buf = String::new();
1381         buf.extend(iterable);
1382         buf
1383     }
1384 }
1385
1386 #[stable(feature = "rust1", since = "1.0.0")]
1387 impl Extend<char> for String {
1388     fn extend<I: IntoIterator<Item = char>>(&mut self, iterable: I) {
1389         let iterator = iterable.into_iter();
1390         let (lower_bound, _) = iterator.size_hint();
1391         self.reserve(lower_bound);
1392         for ch in iterator {
1393             self.push(ch)
1394         }
1395     }
1396 }
1397
1398 #[stable(feature = "extend_ref", since = "1.2.0")]
1399 impl<'a> Extend<&'a char> for String {
1400     fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iterable: I) {
1401         self.extend(iterable.into_iter().cloned());
1402     }
1403 }
1404
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 impl<'a> Extend<&'a str> for String {
1407     fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iterable: I) {
1408         for s in iterable {
1409             self.push_str(s)
1410         }
1411     }
1412 }
1413
1414 #[stable(feature = "extend_string", since = "1.4.0")]
1415 impl Extend<String> for String {
1416     fn extend<I: IntoIterator<Item = String>>(&mut self, iterable: I) {
1417         for s in iterable {
1418             self.push_str(&s)
1419         }
1420     }
1421 }
1422
1423 /// A convenience impl that delegates to the impl for `&str`
1424 #[unstable(feature = "pattern",
1425            reason = "API not fully fleshed out and ready to be stabilized",
1426            issue = "27721")]
1427 impl<'a, 'b> Pattern<'a> for &'b String {
1428     type Searcher = <&'b str as Pattern<'a>>::Searcher;
1429
1430     fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1431         self[..].into_searcher(haystack)
1432     }
1433
1434     #[inline]
1435     fn is_contained_in(self, haystack: &'a str) -> bool {
1436         self[..].is_contained_in(haystack)
1437     }
1438
1439     #[inline]
1440     fn is_prefix_of(self, haystack: &'a str) -> bool {
1441         self[..].is_prefix_of(haystack)
1442     }
1443 }
1444
1445 #[stable(feature = "rust1", since = "1.0.0")]
1446 impl PartialEq for String {
1447     #[inline]
1448     fn eq(&self, other: &String) -> bool {
1449         PartialEq::eq(&self[..], &other[..])
1450     }
1451     #[inline]
1452     fn ne(&self, other: &String) -> bool {
1453         PartialEq::ne(&self[..], &other[..])
1454     }
1455 }
1456
1457 macro_rules! impl_eq {
1458     ($lhs:ty, $rhs: ty) => {
1459         #[stable(feature = "rust1", since = "1.0.0")]
1460         impl<'a, 'b> PartialEq<$rhs> for $lhs {
1461             #[inline]
1462             fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1463             #[inline]
1464             fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1465         }
1466
1467         #[stable(feature = "rust1", since = "1.0.0")]
1468         impl<'a, 'b> PartialEq<$lhs> for $rhs {
1469             #[inline]
1470             fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1471             #[inline]
1472             fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1473         }
1474
1475     }
1476 }
1477
1478 impl_eq! { String, str }
1479 impl_eq! { String, &'a str }
1480 impl_eq! { Cow<'a, str>, str }
1481 impl_eq! { Cow<'a, str>, &'b str }
1482 impl_eq! { Cow<'a, str>, String }
1483
1484 #[stable(feature = "rust1", since = "1.0.0")]
1485 impl Default for String {
1486     #[inline]
1487     fn default() -> String {
1488         String::new()
1489     }
1490 }
1491
1492 #[stable(feature = "rust1", since = "1.0.0")]
1493 impl fmt::Display for String {
1494     #[inline]
1495     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1496         fmt::Display::fmt(&**self, f)
1497     }
1498 }
1499
1500 #[stable(feature = "rust1", since = "1.0.0")]
1501 impl fmt::Debug for String {
1502     #[inline]
1503     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1504         fmt::Debug::fmt(&**self, f)
1505     }
1506 }
1507
1508 #[stable(feature = "rust1", since = "1.0.0")]
1509 impl hash::Hash for String {
1510     #[inline]
1511     fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1512         (**self).hash(hasher)
1513     }
1514 }
1515
1516 #[stable(feature = "rust1", since = "1.0.0")]
1517 impl<'a> Add<&'a str> for String {
1518     type Output = String;
1519
1520     #[inline]
1521     fn add(mut self, other: &str) -> String {
1522         self.push_str(other);
1523         self
1524     }
1525 }
1526
1527 #[stable(feature = "rust1", since = "1.0.0")]
1528 impl ops::Index<ops::Range<usize>> for String {
1529     type Output = str;
1530
1531     #[inline]
1532     fn index(&self, index: ops::Range<usize>) -> &str {
1533         &self[..][index]
1534     }
1535 }
1536 #[stable(feature = "rust1", since = "1.0.0")]
1537 impl ops::Index<ops::RangeTo<usize>> for String {
1538     type Output = str;
1539
1540     #[inline]
1541     fn index(&self, index: ops::RangeTo<usize>) -> &str {
1542         &self[..][index]
1543     }
1544 }
1545 #[stable(feature = "rust1", since = "1.0.0")]
1546 impl ops::Index<ops::RangeFrom<usize>> for String {
1547     type Output = str;
1548
1549     #[inline]
1550     fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1551         &self[..][index]
1552     }
1553 }
1554 #[stable(feature = "rust1", since = "1.0.0")]
1555 impl ops::Index<ops::RangeFull> for String {
1556     type Output = str;
1557
1558     #[inline]
1559     fn index(&self, _index: ops::RangeFull) -> &str {
1560         unsafe { str::from_utf8_unchecked(&self.vec) }
1561     }
1562 }
1563
1564 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1565 impl ops::IndexMut<ops::Range<usize>> for String {
1566     #[inline]
1567     fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1568         &mut self[..][index]
1569     }
1570 }
1571 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1572 impl ops::IndexMut<ops::RangeTo<usize>> for String {
1573     #[inline]
1574     fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1575         &mut self[..][index]
1576     }
1577 }
1578 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1579 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
1580     #[inline]
1581     fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1582         &mut self[..][index]
1583     }
1584 }
1585 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1586 impl ops::IndexMut<ops::RangeFull> for String {
1587     #[inline]
1588     fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1589         unsafe { mem::transmute(&mut *self.vec) }
1590     }
1591 }
1592
1593 #[stable(feature = "rust1", since = "1.0.0")]
1594 impl ops::Deref for String {
1595     type Target = str;
1596
1597     #[inline]
1598     fn deref(&self) -> &str {
1599         unsafe { str::from_utf8_unchecked(&self.vec) }
1600     }
1601 }
1602
1603 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1604 impl ops::DerefMut for String {
1605     #[inline]
1606     fn deref_mut(&mut self) -> &mut str {
1607         unsafe { mem::transmute(&mut *self.vec) }
1608     }
1609 }
1610
1611 /// An error when parsing a `String`.
1612 ///
1613 /// This `enum` is slightly awkward: it will never actually exist. This error is
1614 /// part of the type signature of the implementation of [`FromStr`] on
1615 /// [`String`]. The return type of [`from_str()`], requires that an error be
1616 /// defined, but, given that a [`String`] can always be made into a new
1617 /// [`String`] without error, this type will never actually be returned. As
1618 /// such, it is only here to satisfy said signature, and is useless otherwise.
1619 ///
1620 /// [`FromStr`]: ../str/trait.FromStr.html
1621 /// [`String`]: struct.String.html
1622 /// [`from_str()`]: ../str/trait.FromStr.html#tymethod.from_str
1623 #[stable(feature = "str_parse_error", since = "1.5.0")]
1624 #[derive(Copy)]
1625 pub enum ParseError {}
1626
1627 #[stable(feature = "rust1", since = "1.0.0")]
1628 impl FromStr for String {
1629     type Err = ParseError;
1630     #[inline]
1631     fn from_str(s: &str) -> Result<String, ParseError> {
1632         Ok(String::from(s))
1633     }
1634 }
1635
1636 #[stable(feature = "str_parse_error", since = "1.5.0")]
1637 impl Clone for ParseError {
1638     fn clone(&self) -> ParseError {
1639         match *self {}
1640     }
1641 }
1642
1643 #[stable(feature = "str_parse_error", since = "1.5.0")]
1644 impl fmt::Debug for ParseError {
1645     fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1646         match *self {}
1647     }
1648 }
1649
1650 #[stable(feature = "str_parse_error", since = "1.5.0")]
1651 impl PartialEq for ParseError {
1652     fn eq(&self, _: &ParseError) -> bool {
1653         match *self {}
1654     }
1655 }
1656
1657 #[stable(feature = "str_parse_error", since = "1.5.0")]
1658 impl Eq for ParseError {}
1659
1660 /// A trait for converting a value to a `String`.
1661 ///
1662 /// This trait is automatically implemented for any type which implements the
1663 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
1664 /// [`Display`] should be implemented instead, and you get the `ToString`
1665 /// implementation for free.
1666 ///
1667 /// [`Display`]: ../fmt/trait.Display.html
1668 #[stable(feature = "rust1", since = "1.0.0")]
1669 pub trait ToString {
1670     /// Converts the given value to a `String`.
1671     ///
1672     /// # Examples
1673     ///
1674     /// Basic usage:
1675     ///
1676     /// ```
1677     /// let i = 5;
1678     /// let five = String::from("5");
1679     ///
1680     /// assert_eq!(five, i.to_string());
1681     /// ```
1682     #[stable(feature = "rust1", since = "1.0.0")]
1683     fn to_string(&self) -> String;
1684 }
1685
1686 #[stable(feature = "rust1", since = "1.0.0")]
1687 impl<T: fmt::Display + ?Sized> ToString for T {
1688     #[inline]
1689     fn to_string(&self) -> String {
1690         use core::fmt::Write;
1691         let mut buf = String::new();
1692         let _ = buf.write_fmt(format_args!("{}", self));
1693         buf.shrink_to_fit();
1694         buf
1695     }
1696 }
1697
1698 #[stable(feature = "rust1", since = "1.0.0")]
1699 impl AsRef<str> for String {
1700     #[inline]
1701     fn as_ref(&self) -> &str {
1702         self
1703     }
1704 }
1705
1706 #[stable(feature = "rust1", since = "1.0.0")]
1707 impl AsRef<[u8]> for String {
1708     #[inline]
1709     fn as_ref(&self) -> &[u8] {
1710         self.as_bytes()
1711     }
1712 }
1713
1714 #[stable(feature = "rust1", since = "1.0.0")]
1715 impl<'a> From<&'a str> for String {
1716     #[cfg(not(test))]
1717     #[inline]
1718     fn from(s: &'a str) -> String {
1719         String { vec: <[_]>::to_vec(s.as_bytes()) }
1720     }
1721
1722     // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1723     // required for this method definition, is not available. Since we don't
1724     // require this method for testing purposes, I'll just stub it
1725     // NB see the slice::hack module in slice.rs for more information
1726     #[inline]
1727     #[cfg(test)]
1728     fn from(_: &str) -> String {
1729         panic!("not available with cfg(test)");
1730     }
1731 }
1732
1733 #[stable(feature = "rust1", since = "1.0.0")]
1734 impl<'a> From<&'a str> for Cow<'a, str> {
1735     #[inline]
1736     fn from(s: &'a str) -> Cow<'a, str> {
1737         Cow::Borrowed(s)
1738     }
1739 }
1740
1741 #[stable(feature = "rust1", since = "1.0.0")]
1742 impl<'a> From<String> for Cow<'a, str> {
1743     #[inline]
1744     fn from(s: String) -> Cow<'a, str> {
1745         Cow::Owned(s)
1746     }
1747 }
1748
1749 #[stable(feature = "rust1", since = "1.0.0")]
1750 impl Into<Vec<u8>> for String {
1751     fn into(self) -> Vec<u8> {
1752         self.into_bytes()
1753     }
1754 }
1755
1756 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`",
1757            issue= "27735")]
1758 impl IntoCow<'static, str> for String {
1759     #[inline]
1760     fn into_cow(self) -> Cow<'static, str> {
1761         Cow::Owned(self)
1762     }
1763 }
1764
1765 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`",
1766            issue = "27735")]
1767 impl<'a> IntoCow<'a, str> for &'a str {
1768     #[inline]
1769     fn into_cow(self) -> Cow<'a, str> {
1770         Cow::Borrowed(self)
1771     }
1772 }
1773
1774 #[stable(feature = "rust1", since = "1.0.0")]
1775 impl fmt::Write for String {
1776     #[inline]
1777     fn write_str(&mut self, s: &str) -> fmt::Result {
1778         self.push_str(s);
1779         Ok(())
1780     }
1781
1782     #[inline]
1783     fn write_char(&mut self, c: char) -> fmt::Result {
1784         self.push(c);
1785         Ok(())
1786     }
1787 }
1788
1789 /// A draining iterator for `String`.
1790 #[stable(feature = "drain", since = "1.6.0")]
1791 pub struct Drain<'a> {
1792     /// Will be used as &'a mut String in the destructor
1793     string: *mut String,
1794     /// Start of part to remove
1795     start: usize,
1796     /// End of part to remove
1797     end: usize,
1798     /// Current remaining range to remove
1799     iter: Chars<'a>,
1800 }
1801
1802 #[stable(feature = "drain", since = "1.6.0")]
1803 unsafe impl<'a> Sync for Drain<'a> {}
1804 #[stable(feature = "drain", since = "1.6.0")]
1805 unsafe impl<'a> Send for Drain<'a> {}
1806
1807 #[stable(feature = "drain", since = "1.6.0")]
1808 impl<'a> Drop for Drain<'a> {
1809     fn drop(&mut self) {
1810         unsafe {
1811             // Use Vec::drain. "Reaffirm" the bounds checks to avoid
1812             // panic code being inserted again.
1813             let self_vec = (*self.string).as_mut_vec();
1814             if self.start <= self.end && self.end <= self_vec.len() {
1815                 self_vec.drain(self.start..self.end);
1816             }
1817         }
1818     }
1819 }
1820
1821 #[stable(feature = "drain", since = "1.6.0")]
1822 impl<'a> Iterator for Drain<'a> {
1823     type Item = char;
1824
1825     #[inline]
1826     fn next(&mut self) -> Option<char> {
1827         self.iter.next()
1828     }
1829
1830     fn size_hint(&self) -> (usize, Option<usize>) {
1831         self.iter.size_hint()
1832     }
1833 }
1834
1835 #[stable(feature = "drain", since = "1.6.0")]
1836 impl<'a> DoubleEndedIterator for Drain<'a> {
1837     #[inline]
1838     fn next_back(&mut self) -> Option<char> {
1839         self.iter.next_back()
1840     }
1841 }