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