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