]> git.proxmox.com Git - rustc.git/blob - src/liballoc/string.rs
New upstream version 1.29.0+dfsg1
[rustc.git] / src / liballoc / 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::char::{decode_utf16, REPLACEMENT_CHARACTER};
60 use core::fmt;
61 use core::hash;
62 use core::iter::{FromIterator, FusedIterator};
63 use core::ops::Bound::{Excluded, Included, Unbounded};
64 use core::ops::{self, Add, AddAssign, Index, IndexMut, RangeBounds};
65 use core::ptr;
66 use core::str::pattern::Pattern;
67 use core::str::lossy;
68
69 use collections::CollectionAllocErr;
70 use borrow::{Cow, ToOwned};
71 use boxed::Box;
72 use str::{self, from_boxed_utf8_unchecked, FromStr, Utf8Error, Chars};
73 use vec::Vec;
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 /// [`String::from`]: #method.from
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 /// ```compile_fail,E0277
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 a
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 /// This will create a [`&str`] from the `String` and pass it in. This
160 /// conversion is very inexpensive, and so generally, functions will accept
161 /// [`&str`]s as arguments unless they need a `String` for some specific
162 /// reason.
163 ///
164 /// In certain cases Rust doesn't have enough information to make this
165 /// conversion, known as [`Deref`] coercion. In the following example a string
166 /// slice [`&'a str`][`&str`] implements the trait `TraitExample`, and the function
167 /// `example_func` takes anything that implements the trait. In this case Rust
168 /// would need to make two implicit conversions, which Rust doesn't have the
169 /// means to do. For that reason, the following example will not compile.
170 ///
171 /// ```compile_fail,E0277
172 /// trait TraitExample {}
173 ///
174 /// impl<'a> TraitExample for &'a str {}
175 ///
176 /// fn example_func<A: TraitExample>(example_arg: A) {}
177 ///
178 /// fn main() {
179 /// let example_string = String::from("example_string");
180 /// example_func(&example_string);
181 /// }
182 /// ```
183 ///
184 /// There are two options that would work instead. The first would be to
185 /// change the line `example_func(&example_string);` to
186 /// `example_func(example_string.as_str());`, using the method [`as_str()`]
187 /// to explicitly extract the string slice containing the string. The second
188 /// way changes `example_func(&example_string);` to
189 /// `example_func(&*example_string);`. In this case we are dereferencing a
190 /// `String` to a [`str`][`&str`], then referencing the [`str`][`&str`] back to
191 /// [`&str`]. The second way is more idiomatic, however both work to do the
192 /// conversion explicitly rather than relying on the implicit conversion.
193 ///
194 /// # Representation
195 ///
196 /// A `String` is made up of three components: a pointer to some bytes, a
197 /// length, and a capacity. The pointer points to an internal buffer `String`
198 /// uses to store its data. The length is the number of bytes currently stored
199 /// in the buffer, and the capacity is the size of the buffer in bytes. As such,
200 /// the length will always be less than or equal to the capacity.
201 ///
202 /// This buffer is always stored on the heap.
203 ///
204 /// You can look at these with the [`as_ptr`], [`len`], and [`capacity`]
205 /// methods:
206 ///
207 /// ```
208 /// use std::mem;
209 ///
210 /// let story = String::from("Once upon a time...");
211 ///
212 /// let ptr = story.as_ptr();
213 /// let len = story.len();
214 /// let capacity = story.capacity();
215 ///
216 /// // story has nineteen bytes
217 /// assert_eq!(19, len);
218 ///
219 /// // Now that we have our parts, we throw the story away.
220 /// mem::forget(story);
221 ///
222 /// // We can re-build a String out of ptr, len, and capacity. This is all
223 /// // unsafe because we are responsible for making sure the components are
224 /// // valid:
225 /// let s = unsafe { String::from_raw_parts(ptr as *mut _, len, capacity) } ;
226 ///
227 /// assert_eq!(String::from("Once upon a time..."), s);
228 /// ```
229 ///
230 /// [`as_ptr`]: #method.as_ptr
231 /// [`len`]: #method.len
232 /// [`capacity`]: #method.capacity
233 ///
234 /// If a `String` has enough capacity, adding elements to it will not
235 /// re-allocate. For example, consider this program:
236 ///
237 /// ```
238 /// let mut s = String::new();
239 ///
240 /// println!("{}", s.capacity());
241 ///
242 /// for _ in 0..5 {
243 /// s.push_str("hello");
244 /// println!("{}", s.capacity());
245 /// }
246 /// ```
247 ///
248 /// This will output the following:
249 ///
250 /// ```text
251 /// 0
252 /// 5
253 /// 10
254 /// 20
255 /// 20
256 /// 40
257 /// ```
258 ///
259 /// At first, we have no memory allocated at all, but as we append to the
260 /// string, it increases its capacity appropriately. If we instead use the
261 /// [`with_capacity`] method to allocate the correct capacity initially:
262 ///
263 /// ```
264 /// let mut s = String::with_capacity(25);
265 ///
266 /// println!("{}", s.capacity());
267 ///
268 /// for _ in 0..5 {
269 /// s.push_str("hello");
270 /// println!("{}", s.capacity());
271 /// }
272 /// ```
273 ///
274 /// [`with_capacity`]: #method.with_capacity
275 ///
276 /// We end up with a different output:
277 ///
278 /// ```text
279 /// 25
280 /// 25
281 /// 25
282 /// 25
283 /// 25
284 /// 25
285 /// ```
286 ///
287 /// Here, there's no need to allocate more memory inside the loop.
288 ///
289 /// [`&str`]: ../../std/primitive.str.html
290 /// [`Deref`]: ../../std/ops/trait.Deref.html
291 /// [`as_str()`]: struct.String.html#method.as_str
292 #[derive(PartialOrd, Eq, Ord)]
293 #[stable(feature = "rust1", since = "1.0.0")]
294 pub struct String {
295 vec: Vec<u8>,
296 }
297
298 /// A possible error value when converting a `String` from a UTF-8 byte vector.
299 ///
300 /// This type is the error type for the [`from_utf8`] method on [`String`]. It
301 /// is designed in such a way to carefully avoid reallocations: the
302 /// [`into_bytes`] method will give back the byte vector that was used in the
303 /// conversion attempt.
304 ///
305 /// [`from_utf8`]: struct.String.html#method.from_utf8
306 /// [`String`]: struct.String.html
307 /// [`into_bytes`]: struct.FromUtf8Error.html#method.into_bytes
308 ///
309 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
310 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
311 /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
312 /// through the [`utf8_error`] method.
313 ///
314 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
315 /// [`std::str`]: ../../std/str/index.html
316 /// [`u8`]: ../../std/primitive.u8.html
317 /// [`&str`]: ../../std/primitive.str.html
318 /// [`utf8_error`]: #method.utf8_error
319 ///
320 /// # Examples
321 ///
322 /// Basic usage:
323 ///
324 /// ```
325 /// // some invalid bytes, in a vector
326 /// let bytes = vec![0, 159];
327 ///
328 /// let value = String::from_utf8(bytes);
329 ///
330 /// assert!(value.is_err());
331 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
332 /// ```
333 #[stable(feature = "rust1", since = "1.0.0")]
334 #[derive(Debug)]
335 pub struct FromUtf8Error {
336 bytes: Vec<u8>,
337 error: Utf8Error,
338 }
339
340 /// A possible error value when converting a `String` from a UTF-16 byte slice.
341 ///
342 /// This type is the error type for the [`from_utf16`] method on [`String`].
343 ///
344 /// [`from_utf16`]: struct.String.html#method.from_utf16
345 /// [`String`]: struct.String.html
346 ///
347 /// # Examples
348 ///
349 /// Basic usage:
350 ///
351 /// ```
352 /// // 𝄞mu<invalid>ic
353 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
354 /// 0xD800, 0x0069, 0x0063];
355 ///
356 /// assert!(String::from_utf16(v).is_err());
357 /// ```
358 #[stable(feature = "rust1", since = "1.0.0")]
359 #[derive(Debug)]
360 pub struct FromUtf16Error(());
361
362 impl String {
363 /// Creates a new empty `String`.
364 ///
365 /// Given that the `String` is empty, this will not allocate any initial
366 /// buffer. While that means that this initial operation is very
367 /// inexpensive, it may cause excessive allocation later when you add
368 /// data. If you have an idea of how much data the `String` will hold,
369 /// consider the [`with_capacity`] method to prevent excessive
370 /// re-allocation.
371 ///
372 /// [`with_capacity`]: #method.with_capacity
373 ///
374 /// # Examples
375 ///
376 /// Basic usage:
377 ///
378 /// ```
379 /// let s = String::new();
380 /// ```
381 #[inline]
382 #[stable(feature = "rust1", since = "1.0.0")]
383 #[rustc_const_unstable(feature = "const_string_new")]
384 pub const fn new() -> String {
385 String { vec: Vec::new() }
386 }
387
388 /// Creates a new empty `String` with a particular capacity.
389 ///
390 /// `String`s have an internal buffer to hold their data. The capacity is
391 /// the length of that buffer, and can be queried with the [`capacity`]
392 /// method. This method creates an empty `String`, but one with an initial
393 /// buffer that can hold `capacity` bytes. This is useful when you may be
394 /// appending a bunch of data to the `String`, reducing the number of
395 /// reallocations it needs to do.
396 ///
397 /// [`capacity`]: #method.capacity
398 ///
399 /// If the given capacity is `0`, no allocation will occur, and this method
400 /// is identical to the [`new`] method.
401 ///
402 /// [`new`]: #method.new
403 ///
404 /// # Examples
405 ///
406 /// Basic usage:
407 ///
408 /// ```
409 /// let mut s = String::with_capacity(10);
410 ///
411 /// // The String contains no chars, even though it has capacity for more
412 /// assert_eq!(s.len(), 0);
413 ///
414 /// // These are all done without reallocating...
415 /// let cap = s.capacity();
416 /// for i in 0..10 {
417 /// s.push('a');
418 /// }
419 ///
420 /// assert_eq!(s.capacity(), cap);
421 ///
422 /// // ...but this may make the vector reallocate
423 /// s.push('a');
424 /// ```
425 #[inline]
426 #[stable(feature = "rust1", since = "1.0.0")]
427 pub fn with_capacity(capacity: usize) -> String {
428 String { vec: Vec::with_capacity(capacity) }
429 }
430
431 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
432 // required for this method definition, is not available. Since we don't
433 // require this method for testing purposes, I'll just stub it
434 // NB see the slice::hack module in slice.rs for more information
435 #[inline]
436 #[cfg(test)]
437 pub fn from_str(_: &str) -> String {
438 panic!("not available with cfg(test)");
439 }
440
441 /// Converts a vector of bytes to a `String`.
442 ///
443 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a vector of bytes
444 /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
445 /// two. Not all byte slices are valid `String`s, however: `String`
446 /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
447 /// the bytes are valid UTF-8, and then does the conversion.
448 ///
449 /// If you are sure that the byte slice is valid UTF-8, and you don't want
450 /// to incur the overhead of the validity check, there is an unsafe version
451 /// of this function, [`from_utf8_unchecked`], which has the same behavior
452 /// but skips the check.
453 ///
454 /// This method will take care to not copy the vector, for efficiency's
455 /// sake.
456 ///
457 /// If you need a [`&str`] instead of a `String`, consider
458 /// [`str::from_utf8`].
459 ///
460 /// The inverse of this method is [`as_bytes`].
461 ///
462 /// # Errors
463 ///
464 /// Returns [`Err`] if the slice is not UTF-8 with a description as to why the
465 /// provided bytes are not UTF-8. The vector you moved in is also included.
466 ///
467 /// # Examples
468 ///
469 /// Basic usage:
470 ///
471 /// ```
472 /// // some bytes, in a vector
473 /// let sparkle_heart = vec![240, 159, 146, 150];
474 ///
475 /// // We know these bytes are valid, so we'll use `unwrap()`.
476 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
477 ///
478 /// assert_eq!("💖", sparkle_heart);
479 /// ```
480 ///
481 /// Incorrect bytes:
482 ///
483 /// ```
484 /// // some invalid bytes, in a vector
485 /// let sparkle_heart = vec![0, 159, 146, 150];
486 ///
487 /// assert!(String::from_utf8(sparkle_heart).is_err());
488 /// ```
489 ///
490 /// See the docs for [`FromUtf8Error`] for more details on what you can do
491 /// with this error.
492 ///
493 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
494 /// [`&str`]: ../../std/primitive.str.html
495 /// [`u8`]: ../../std/primitive.u8.html
496 /// [`Vec<u8>`]: ../../std/vec/struct.Vec.html
497 /// [`str::from_utf8`]: ../../std/str/fn.from_utf8.html
498 /// [`as_bytes`]: struct.String.html#method.as_bytes
499 /// [`FromUtf8Error`]: struct.FromUtf8Error.html
500 /// [`Err`]: ../../stdresult/enum.Result.html#variant.Err
501 #[inline]
502 #[stable(feature = "rust1", since = "1.0.0")]
503 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
504 match str::from_utf8(&vec) {
505 Ok(..) => Ok(String { vec: vec }),
506 Err(e) => {
507 Err(FromUtf8Error {
508 bytes: vec,
509 error: e,
510 })
511 }
512 }
513 }
514
515 /// Converts a slice of bytes to a string, including invalid characters.
516 ///
517 /// Strings are made of bytes ([`u8`]), and a slice of bytes
518 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
519 /// between the two. Not all byte slices are valid strings, however: strings
520 /// are required to be valid UTF-8. During this conversion,
521 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
522 /// `U+FFFD REPLACEMENT CHARACTER`, which looks like this: �
523 ///
524 /// [`u8`]: ../../std/primitive.u8.html
525 /// [byteslice]: ../../std/primitive.slice.html
526 ///
527 /// If you are sure that the byte slice is valid UTF-8, and you don't want
528 /// to incur the overhead of the conversion, there is an unsafe version
529 /// of this function, [`from_utf8_unchecked`], which has the same behavior
530 /// but skips the checks.
531 ///
532 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
533 ///
534 /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
535 /// UTF-8, then we need to insert the replacement characters, which will
536 /// change the size of the string, and hence, require a `String`. But if
537 /// it's already valid UTF-8, we don't need a new allocation. This return
538 /// type allows us to handle both cases.
539 ///
540 /// [`Cow<'a, str>`]: ../../std/borrow/enum.Cow.html
541 ///
542 /// # Examples
543 ///
544 /// Basic usage:
545 ///
546 /// ```
547 /// // some bytes, in a vector
548 /// let sparkle_heart = vec![240, 159, 146, 150];
549 ///
550 /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
551 ///
552 /// assert_eq!("💖", sparkle_heart);
553 /// ```
554 ///
555 /// Incorrect bytes:
556 ///
557 /// ```
558 /// // some invalid bytes
559 /// let input = b"Hello \xF0\x90\x80World";
560 /// let output = String::from_utf8_lossy(input);
561 ///
562 /// assert_eq!("Hello �World", output);
563 /// ```
564 #[stable(feature = "rust1", since = "1.0.0")]
565 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
566 let mut iter = lossy::Utf8Lossy::from_bytes(v).chunks();
567
568 let (first_valid, first_broken) = if let Some(chunk) = iter.next() {
569 let lossy::Utf8LossyChunk { valid, broken } = chunk;
570 if valid.len() == v.len() {
571 debug_assert!(broken.is_empty());
572 return Cow::Borrowed(valid);
573 }
574 (valid, broken)
575 } else {
576 return Cow::Borrowed("");
577 };
578
579 const REPLACEMENT: &'static str = "\u{FFFD}";
580
581 let mut res = String::with_capacity(v.len());
582 res.push_str(first_valid);
583 if !first_broken.is_empty() {
584 res.push_str(REPLACEMENT);
585 }
586
587 for lossy::Utf8LossyChunk { valid, broken } in iter {
588 res.push_str(valid);
589 if !broken.is_empty() {
590 res.push_str(REPLACEMENT);
591 }
592 }
593
594 Cow::Owned(res)
595 }
596
597 /// Decode a UTF-16 encoded vector `v` into a `String`, returning [`Err`]
598 /// if `v` contains any invalid data.
599 ///
600 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
601 ///
602 /// # Examples
603 ///
604 /// Basic usage:
605 ///
606 /// ```
607 /// // 𝄞music
608 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
609 /// 0x0073, 0x0069, 0x0063];
610 /// assert_eq!(String::from("𝄞music"),
611 /// String::from_utf16(v).unwrap());
612 ///
613 /// // 𝄞mu<invalid>ic
614 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
615 /// 0xD800, 0x0069, 0x0063];
616 /// assert!(String::from_utf16(v).is_err());
617 /// ```
618 #[stable(feature = "rust1", since = "1.0.0")]
619 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
620 decode_utf16(v.iter().cloned()).collect::<Result<_, _>>().map_err(|_| FromUtf16Error(()))
621 }
622
623 /// Decode a UTF-16 encoded slice `v` into a `String`, replacing
624 /// invalid data with the replacement character (U+FFFD).
625 ///
626 /// Unlike [`from_utf8_lossy`] which returns a [`Cow<'a, str>`],
627 /// `from_utf16_lossy` returns a `String` since the UTF-16 to UTF-8
628 /// conversion requires a memory allocation.
629 ///
630 /// [`from_utf8_lossy`]: #method.from_utf8_lossy
631 /// [`Cow<'a, str>`]: ../borrow/enum.Cow.html
632 ///
633 /// # Examples
634 ///
635 /// Basic usage:
636 ///
637 /// ```
638 /// // 𝄞mus<invalid>ic<invalid>
639 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
640 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
641 /// 0xD834];
642 ///
643 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
644 /// String::from_utf16_lossy(v));
645 /// ```
646 #[inline]
647 #[stable(feature = "rust1", since = "1.0.0")]
648 pub fn from_utf16_lossy(v: &[u16]) -> String {
649 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
650 }
651
652 /// Creates a new `String` from a length, capacity, and pointer.
653 ///
654 /// # Safety
655 ///
656 /// This is highly unsafe, due to the number of invariants that aren't
657 /// checked:
658 ///
659 /// * The memory at `ptr` needs to have been previously allocated by the
660 /// same allocator the standard library uses.
661 /// * `length` needs to be less than or equal to `capacity`.
662 /// * `capacity` needs to be the correct value.
663 ///
664 /// Violating these may cause problems like corrupting the allocator's
665 /// internal data structures.
666 ///
667 /// The ownership of `ptr` is effectively transferred to the
668 /// `String` which may then deallocate, reallocate or change the
669 /// contents of memory pointed to by the pointer at will. Ensure
670 /// that nothing else uses the pointer after calling this
671 /// function.
672 ///
673 /// # Examples
674 ///
675 /// Basic usage:
676 ///
677 /// ```
678 /// use std::mem;
679 ///
680 /// unsafe {
681 /// let s = String::from("hello");
682 /// let ptr = s.as_ptr();
683 /// let len = s.len();
684 /// let capacity = s.capacity();
685 ///
686 /// mem::forget(s);
687 ///
688 /// let s = String::from_raw_parts(ptr as *mut _, len, capacity);
689 ///
690 /// assert_eq!(String::from("hello"), s);
691 /// }
692 /// ```
693 #[inline]
694 #[stable(feature = "rust1", since = "1.0.0")]
695 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
696 String { vec: Vec::from_raw_parts(buf, length, capacity) }
697 }
698
699 /// Converts a vector of bytes to a `String` without checking that the
700 /// string contains valid UTF-8.
701 ///
702 /// See the safe version, [`from_utf8`], for more details.
703 ///
704 /// [`from_utf8`]: struct.String.html#method.from_utf8
705 ///
706 /// # Safety
707 ///
708 /// This function is unsafe because it does not check that the bytes passed
709 /// to it are valid UTF-8. If this constraint is violated, it may cause
710 /// memory unsafety issues with future users of the `String`, as the rest of
711 /// the standard library assumes that `String`s are valid UTF-8.
712 ///
713 /// # Examples
714 ///
715 /// Basic usage:
716 ///
717 /// ```
718 /// // some bytes, in a vector
719 /// let sparkle_heart = vec![240, 159, 146, 150];
720 ///
721 /// let sparkle_heart = unsafe {
722 /// String::from_utf8_unchecked(sparkle_heart)
723 /// };
724 ///
725 /// assert_eq!("💖", sparkle_heart);
726 /// ```
727 #[inline]
728 #[stable(feature = "rust1", since = "1.0.0")]
729 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
730 String { vec: bytes }
731 }
732
733 /// Converts a `String` into a byte vector.
734 ///
735 /// This consumes the `String`, so we do not need to copy its contents.
736 ///
737 /// # Examples
738 ///
739 /// Basic usage:
740 ///
741 /// ```
742 /// let s = String::from("hello");
743 /// let bytes = s.into_bytes();
744 ///
745 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
746 /// ```
747 #[inline]
748 #[stable(feature = "rust1", since = "1.0.0")]
749 pub fn into_bytes(self) -> Vec<u8> {
750 self.vec
751 }
752
753 /// Extracts a string slice containing the entire string.
754 ///
755 /// # Examples
756 ///
757 /// Basic usage:
758 ///
759 /// ```
760 /// let s = String::from("foo");
761 ///
762 /// assert_eq!("foo", s.as_str());
763 /// ```
764 #[inline]
765 #[stable(feature = "string_as_str", since = "1.7.0")]
766 pub fn as_str(&self) -> &str {
767 self
768 }
769
770 /// Converts a `String` into a mutable string slice.
771 ///
772 /// # Examples
773 ///
774 /// Basic usage:
775 ///
776 /// ```
777 /// let mut s = String::from("foobar");
778 /// let s_mut_str = s.as_mut_str();
779 ///
780 /// s_mut_str.make_ascii_uppercase();
781 ///
782 /// assert_eq!("FOOBAR", s_mut_str);
783 /// ```
784 #[inline]
785 #[stable(feature = "string_as_str", since = "1.7.0")]
786 pub fn as_mut_str(&mut self) -> &mut str {
787 self
788 }
789
790 /// Appends a given string slice onto the end of this `String`.
791 ///
792 /// # Examples
793 ///
794 /// Basic usage:
795 ///
796 /// ```
797 /// let mut s = String::from("foo");
798 ///
799 /// s.push_str("bar");
800 ///
801 /// assert_eq!("foobar", s);
802 /// ```
803 #[inline]
804 #[stable(feature = "rust1", since = "1.0.0")]
805 pub fn push_str(&mut self, string: &str) {
806 self.vec.extend_from_slice(string.as_bytes())
807 }
808
809 /// Returns this `String`'s capacity, in bytes.
810 ///
811 /// # Examples
812 ///
813 /// Basic usage:
814 ///
815 /// ```
816 /// let s = String::with_capacity(10);
817 ///
818 /// assert!(s.capacity() >= 10);
819 /// ```
820 #[inline]
821 #[stable(feature = "rust1", since = "1.0.0")]
822 pub fn capacity(&self) -> usize {
823 self.vec.capacity()
824 }
825
826 /// Ensures that this `String`'s capacity is at least `additional` bytes
827 /// larger than its length.
828 ///
829 /// The capacity may be increased by more than `additional` bytes if it
830 /// chooses, to prevent frequent reallocations.
831 ///
832 /// If you do not want this "at least" behavior, see the [`reserve_exact`]
833 /// method.
834 ///
835 /// # Panics
836 ///
837 /// Panics if the new capacity overflows [`usize`].
838 ///
839 /// [`reserve_exact`]: struct.String.html#method.reserve_exact
840 /// [`usize`]: ../../std/primitive.usize.html
841 ///
842 /// # Examples
843 ///
844 /// Basic usage:
845 ///
846 /// ```
847 /// let mut s = String::new();
848 ///
849 /// s.reserve(10);
850 ///
851 /// assert!(s.capacity() >= 10);
852 /// ```
853 ///
854 /// This may not actually increase the capacity:
855 ///
856 /// ```
857 /// let mut s = String::with_capacity(10);
858 /// s.push('a');
859 /// s.push('b');
860 ///
861 /// // s now has a length of 2 and a capacity of 10
862 /// assert_eq!(2, s.len());
863 /// assert_eq!(10, s.capacity());
864 ///
865 /// // Since we already have an extra 8 capacity, calling this...
866 /// s.reserve(8);
867 ///
868 /// // ... doesn't actually increase.
869 /// assert_eq!(10, s.capacity());
870 /// ```
871 #[inline]
872 #[stable(feature = "rust1", since = "1.0.0")]
873 pub fn reserve(&mut self, additional: usize) {
874 self.vec.reserve(additional)
875 }
876
877 /// Ensures that this `String`'s capacity is `additional` bytes
878 /// larger than its length.
879 ///
880 /// Consider using the [`reserve`] method unless you absolutely know
881 /// better than the allocator.
882 ///
883 /// [`reserve`]: #method.reserve
884 ///
885 /// # Panics
886 ///
887 /// Panics if the new capacity overflows `usize`.
888 ///
889 /// # Examples
890 ///
891 /// Basic usage:
892 ///
893 /// ```
894 /// let mut s = String::new();
895 ///
896 /// s.reserve_exact(10);
897 ///
898 /// assert!(s.capacity() >= 10);
899 /// ```
900 ///
901 /// This may not actually increase the capacity:
902 ///
903 /// ```
904 /// let mut s = String::with_capacity(10);
905 /// s.push('a');
906 /// s.push('b');
907 ///
908 /// // s now has a length of 2 and a capacity of 10
909 /// assert_eq!(2, s.len());
910 /// assert_eq!(10, s.capacity());
911 ///
912 /// // Since we already have an extra 8 capacity, calling this...
913 /// s.reserve_exact(8);
914 ///
915 /// // ... doesn't actually increase.
916 /// assert_eq!(10, s.capacity());
917 /// ```
918 #[inline]
919 #[stable(feature = "rust1", since = "1.0.0")]
920 pub fn reserve_exact(&mut self, additional: usize) {
921 self.vec.reserve_exact(additional)
922 }
923
924 /// Tries to reserve capacity for at least `additional` more elements to be inserted
925 /// in the given `String`. The collection may reserve more space to avoid
926 /// frequent reallocations. After calling `reserve`, capacity will be
927 /// greater than or equal to `self.len() + additional`. Does nothing if
928 /// capacity is already sufficient.
929 ///
930 /// # Errors
931 ///
932 /// If the capacity overflows, or the allocator reports a failure, then an error
933 /// is returned.
934 ///
935 /// # Examples
936 ///
937 /// ```
938 /// #![feature(try_reserve)]
939 /// use std::collections::CollectionAllocErr;
940 ///
941 /// fn process_data(data: &str) -> Result<String, CollectionAllocErr> {
942 /// let mut output = String::new();
943 ///
944 /// // Pre-reserve the memory, exiting if we can't
945 /// output.try_reserve(data.len())?;
946 ///
947 /// // Now we know this can't OOM in the middle of our complex work
948 /// output.push_str(data);
949 ///
950 /// Ok(output)
951 /// }
952 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
953 /// ```
954 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
955 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
956 self.vec.try_reserve(additional)
957 }
958
959 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
960 /// be inserted in the given `String`. After calling `reserve_exact`,
961 /// capacity will be greater than or equal to `self.len() + additional`.
962 /// Does nothing if the capacity is already sufficient.
963 ///
964 /// Note that the allocator may give the collection more space than it
965 /// requests. Therefore capacity can not be relied upon to be precisely
966 /// minimal. Prefer `reserve` if future insertions are expected.
967 ///
968 /// # Errors
969 ///
970 /// If the capacity overflows, or the allocator reports a failure, then an error
971 /// is returned.
972 ///
973 /// # Examples
974 ///
975 /// ```
976 /// #![feature(try_reserve)]
977 /// use std::collections::CollectionAllocErr;
978 ///
979 /// fn process_data(data: &str) -> Result<String, CollectionAllocErr> {
980 /// let mut output = String::new();
981 ///
982 /// // Pre-reserve the memory, exiting if we can't
983 /// output.try_reserve(data.len())?;
984 ///
985 /// // Now we know this can't OOM in the middle of our complex work
986 /// output.push_str(data);
987 ///
988 /// Ok(output)
989 /// }
990 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
991 /// ```
992 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
993 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
994 self.vec.try_reserve_exact(additional)
995 }
996
997 /// Shrinks the capacity of this `String` to match its length.
998 ///
999 /// # Examples
1000 ///
1001 /// Basic usage:
1002 ///
1003 /// ```
1004 /// let mut s = String::from("foo");
1005 ///
1006 /// s.reserve(100);
1007 /// assert!(s.capacity() >= 100);
1008 ///
1009 /// s.shrink_to_fit();
1010 /// assert_eq!(3, s.capacity());
1011 /// ```
1012 #[inline]
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 pub fn shrink_to_fit(&mut self) {
1015 self.vec.shrink_to_fit()
1016 }
1017
1018 /// Shrinks the capacity of this `String` with a lower bound.
1019 ///
1020 /// The capacity will remain at least as large as both the length
1021 /// and the supplied value.
1022 ///
1023 /// Panics if the current capacity is smaller than the supplied
1024 /// minimum capacity.
1025 ///
1026 /// # Examples
1027 ///
1028 /// ```
1029 /// #![feature(shrink_to)]
1030 /// let mut s = String::from("foo");
1031 ///
1032 /// s.reserve(100);
1033 /// assert!(s.capacity() >= 100);
1034 ///
1035 /// s.shrink_to(10);
1036 /// assert!(s.capacity() >= 10);
1037 /// s.shrink_to(0);
1038 /// assert!(s.capacity() >= 3);
1039 /// ```
1040 #[inline]
1041 #[unstable(feature = "shrink_to", reason = "new API", issue="0")]
1042 pub fn shrink_to(&mut self, min_capacity: usize) {
1043 self.vec.shrink_to(min_capacity)
1044 }
1045
1046 /// Appends the given [`char`] to the end of this `String`.
1047 ///
1048 /// [`char`]: ../../std/primitive.char.html
1049 ///
1050 /// # Examples
1051 ///
1052 /// Basic usage:
1053 ///
1054 /// ```
1055 /// let mut s = String::from("abc");
1056 ///
1057 /// s.push('1');
1058 /// s.push('2');
1059 /// s.push('3');
1060 ///
1061 /// assert_eq!("abc123", s);
1062 /// ```
1063 #[inline]
1064 #[stable(feature = "rust1", since = "1.0.0")]
1065 pub fn push(&mut self, ch: char) {
1066 match ch.len_utf8() {
1067 1 => self.vec.push(ch as u8),
1068 _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
1069 }
1070 }
1071
1072 /// Returns a byte slice of this `String`'s contents.
1073 ///
1074 /// The inverse of this method is [`from_utf8`].
1075 ///
1076 /// [`from_utf8`]: #method.from_utf8
1077 ///
1078 /// # Examples
1079 ///
1080 /// Basic usage:
1081 ///
1082 /// ```
1083 /// let s = String::from("hello");
1084 ///
1085 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
1086 /// ```
1087 #[inline]
1088 #[stable(feature = "rust1", since = "1.0.0")]
1089 pub fn as_bytes(&self) -> &[u8] {
1090 &self.vec
1091 }
1092
1093 /// Shortens this `String` to the specified length.
1094 ///
1095 /// If `new_len` is greater than the string's current length, this has no
1096 /// effect.
1097 ///
1098 /// Note that this method has no effect on the allocated capacity
1099 /// of the string
1100 ///
1101 /// # Panics
1102 ///
1103 /// Panics if `new_len` does not lie on a [`char`] boundary.
1104 ///
1105 /// [`char`]: ../../std/primitive.char.html
1106 ///
1107 /// # Examples
1108 ///
1109 /// Basic usage:
1110 ///
1111 /// ```
1112 /// let mut s = String::from("hello");
1113 ///
1114 /// s.truncate(2);
1115 ///
1116 /// assert_eq!("he", s);
1117 /// ```
1118 #[inline]
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 pub fn truncate(&mut self, new_len: usize) {
1121 if new_len <= self.len() {
1122 assert!(self.is_char_boundary(new_len));
1123 self.vec.truncate(new_len)
1124 }
1125 }
1126
1127 /// Removes the last character from the string buffer and returns it.
1128 ///
1129 /// Returns [`None`] if this `String` is empty.
1130 ///
1131 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1132 ///
1133 /// # Examples
1134 ///
1135 /// Basic usage:
1136 ///
1137 /// ```
1138 /// let mut s = String::from("foo");
1139 ///
1140 /// assert_eq!(s.pop(), Some('o'));
1141 /// assert_eq!(s.pop(), Some('o'));
1142 /// assert_eq!(s.pop(), Some('f'));
1143 ///
1144 /// assert_eq!(s.pop(), None);
1145 /// ```
1146 #[inline]
1147 #[stable(feature = "rust1", since = "1.0.0")]
1148 pub fn pop(&mut self) -> Option<char> {
1149 let ch = self.chars().rev().next()?;
1150 let newlen = self.len() - ch.len_utf8();
1151 unsafe {
1152 self.vec.set_len(newlen);
1153 }
1154 Some(ch)
1155 }
1156
1157 /// Removes a [`char`] from this `String` at a byte position and returns it.
1158 ///
1159 /// This is an `O(n)` operation, as it requires copying every element in the
1160 /// buffer.
1161 ///
1162 /// # Panics
1163 ///
1164 /// Panics if `idx` is larger than or equal to the `String`'s length,
1165 /// or if it does not lie on a [`char`] boundary.
1166 ///
1167 /// [`char`]: ../../std/primitive.char.html
1168 ///
1169 /// # Examples
1170 ///
1171 /// Basic usage:
1172 ///
1173 /// ```
1174 /// let mut s = String::from("foo");
1175 ///
1176 /// assert_eq!(s.remove(0), 'f');
1177 /// assert_eq!(s.remove(1), 'o');
1178 /// assert_eq!(s.remove(0), 'o');
1179 /// ```
1180 #[inline]
1181 #[stable(feature = "rust1", since = "1.0.0")]
1182 pub fn remove(&mut self, idx: usize) -> char {
1183 let ch = match self[idx..].chars().next() {
1184 Some(ch) => ch,
1185 None => panic!("cannot remove a char from the end of a string"),
1186 };
1187
1188 let next = idx + ch.len_utf8();
1189 let len = self.len();
1190 unsafe {
1191 ptr::copy(self.vec.as_ptr().offset(next as isize),
1192 self.vec.as_mut_ptr().offset(idx as isize),
1193 len - next);
1194 self.vec.set_len(len - (next - idx));
1195 }
1196 ch
1197 }
1198
1199 /// Retains only the characters specified by the predicate.
1200 ///
1201 /// In other words, remove all characters `c` such that `f(c)` returns `false`.
1202 /// This method operates in place and preserves the order of the retained
1203 /// characters.
1204 ///
1205 /// # Examples
1206 ///
1207 /// ```
1208 /// let mut s = String::from("f_o_ob_ar");
1209 ///
1210 /// s.retain(|c| c != '_');
1211 ///
1212 /// assert_eq!(s, "foobar");
1213 /// ```
1214 #[inline]
1215 #[stable(feature = "string_retain", since = "1.26.0")]
1216 pub fn retain<F>(&mut self, mut f: F)
1217 where F: FnMut(char) -> bool
1218 {
1219 let len = self.len();
1220 let mut del_bytes = 0;
1221 let mut idx = 0;
1222
1223 while idx < len {
1224 let ch = unsafe {
1225 self.get_unchecked(idx..len).chars().next().unwrap()
1226 };
1227 let ch_len = ch.len_utf8();
1228
1229 if !f(ch) {
1230 del_bytes += ch_len;
1231 } else if del_bytes > 0 {
1232 unsafe {
1233 ptr::copy(self.vec.as_ptr().offset(idx as isize),
1234 self.vec.as_mut_ptr().offset((idx - del_bytes) as isize),
1235 ch_len);
1236 }
1237 }
1238
1239 // Point idx to the next char
1240 idx += ch_len;
1241 }
1242
1243 if del_bytes > 0 {
1244 unsafe { self.vec.set_len(len - del_bytes); }
1245 }
1246 }
1247
1248 /// Inserts a character into this `String` at a byte position.
1249 ///
1250 /// This is an `O(n)` operation as it requires copying every element in the
1251 /// buffer.
1252 ///
1253 /// # Panics
1254 ///
1255 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1256 /// lie on a [`char`] boundary.
1257 ///
1258 /// [`char`]: ../../std/primitive.char.html
1259 ///
1260 /// # Examples
1261 ///
1262 /// Basic usage:
1263 ///
1264 /// ```
1265 /// let mut s = String::with_capacity(3);
1266 ///
1267 /// s.insert(0, 'f');
1268 /// s.insert(1, 'o');
1269 /// s.insert(2, 'o');
1270 ///
1271 /// assert_eq!("foo", s);
1272 /// ```
1273 #[inline]
1274 #[stable(feature = "rust1", since = "1.0.0")]
1275 pub fn insert(&mut self, idx: usize, ch: char) {
1276 assert!(self.is_char_boundary(idx));
1277 let mut bits = [0; 4];
1278 let bits = ch.encode_utf8(&mut bits).as_bytes();
1279
1280 unsafe {
1281 self.insert_bytes(idx, bits);
1282 }
1283 }
1284
1285 unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
1286 let len = self.len();
1287 let amt = bytes.len();
1288 self.vec.reserve(amt);
1289
1290 ptr::copy(self.vec.as_ptr().offset(idx as isize),
1291 self.vec.as_mut_ptr().offset((idx + amt) as isize),
1292 len - idx);
1293 ptr::copy(bytes.as_ptr(),
1294 self.vec.as_mut_ptr().offset(idx as isize),
1295 amt);
1296 self.vec.set_len(len + amt);
1297 }
1298
1299 /// Inserts a string slice into this `String` at a byte position.
1300 ///
1301 /// This is an `O(n)` operation as it requires copying every element in the
1302 /// buffer.
1303 ///
1304 /// # Panics
1305 ///
1306 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1307 /// lie on a [`char`] boundary.
1308 ///
1309 /// [`char`]: ../../std/primitive.char.html
1310 ///
1311 /// # Examples
1312 ///
1313 /// Basic usage:
1314 ///
1315 /// ```
1316 /// let mut s = String::from("bar");
1317 ///
1318 /// s.insert_str(0, "foo");
1319 ///
1320 /// assert_eq!("foobar", s);
1321 /// ```
1322 #[inline]
1323 #[stable(feature = "insert_str", since = "1.16.0")]
1324 pub fn insert_str(&mut self, idx: usize, string: &str) {
1325 assert!(self.is_char_boundary(idx));
1326
1327 unsafe {
1328 self.insert_bytes(idx, string.as_bytes());
1329 }
1330 }
1331
1332 /// Returns a mutable reference to the contents of this `String`.
1333 ///
1334 /// # Safety
1335 ///
1336 /// This function is unsafe because it does not check that the bytes passed
1337 /// to it are valid UTF-8. If this constraint is violated, it may cause
1338 /// memory unsafety issues with future users of the `String`, as the rest of
1339 /// the standard library assumes that `String`s are valid UTF-8.
1340 ///
1341 /// # Examples
1342 ///
1343 /// Basic usage:
1344 ///
1345 /// ```
1346 /// let mut s = String::from("hello");
1347 ///
1348 /// unsafe {
1349 /// let vec = s.as_mut_vec();
1350 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1351 ///
1352 /// vec.reverse();
1353 /// }
1354 /// assert_eq!(s, "olleh");
1355 /// ```
1356 #[inline]
1357 #[stable(feature = "rust1", since = "1.0.0")]
1358 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1359 &mut self.vec
1360 }
1361
1362 /// Returns the length of this `String`, in bytes.
1363 ///
1364 /// # Examples
1365 ///
1366 /// Basic usage:
1367 ///
1368 /// ```
1369 /// let a = String::from("foo");
1370 ///
1371 /// assert_eq!(a.len(), 3);
1372 /// ```
1373 #[inline]
1374 #[stable(feature = "rust1", since = "1.0.0")]
1375 pub fn len(&self) -> usize {
1376 self.vec.len()
1377 }
1378
1379 /// Returns `true` if this `String` has a length of zero.
1380 ///
1381 /// Returns `false` otherwise.
1382 ///
1383 /// # Examples
1384 ///
1385 /// Basic usage:
1386 ///
1387 /// ```
1388 /// let mut v = String::new();
1389 /// assert!(v.is_empty());
1390 ///
1391 /// v.push('a');
1392 /// assert!(!v.is_empty());
1393 /// ```
1394 #[inline]
1395 #[stable(feature = "rust1", since = "1.0.0")]
1396 pub fn is_empty(&self) -> bool {
1397 self.len() == 0
1398 }
1399
1400 /// Splits the string into two at the given index.
1401 ///
1402 /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1403 /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1404 /// boundary of a UTF-8 code point.
1405 ///
1406 /// Note that the capacity of `self` does not change.
1407 ///
1408 /// # Panics
1409 ///
1410 /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1411 /// code point of the string.
1412 ///
1413 /// # Examples
1414 ///
1415 /// ```
1416 /// # fn main() {
1417 /// let mut hello = String::from("Hello, World!");
1418 /// let world = hello.split_off(7);
1419 /// assert_eq!(hello, "Hello, ");
1420 /// assert_eq!(world, "World!");
1421 /// # }
1422 /// ```
1423 #[inline]
1424 #[stable(feature = "string_split_off", since = "1.16.0")]
1425 pub fn split_off(&mut self, at: usize) -> String {
1426 assert!(self.is_char_boundary(at));
1427 let other = self.vec.split_off(at);
1428 unsafe { String::from_utf8_unchecked(other) }
1429 }
1430
1431 /// Truncates this `String`, removing all contents.
1432 ///
1433 /// While this means the `String` will have a length of zero, it does not
1434 /// touch its capacity.
1435 ///
1436 /// # Examples
1437 ///
1438 /// Basic usage:
1439 ///
1440 /// ```
1441 /// let mut s = String::from("foo");
1442 ///
1443 /// s.clear();
1444 ///
1445 /// assert!(s.is_empty());
1446 /// assert_eq!(0, s.len());
1447 /// assert_eq!(3, s.capacity());
1448 /// ```
1449 #[inline]
1450 #[stable(feature = "rust1", since = "1.0.0")]
1451 pub fn clear(&mut self) {
1452 self.vec.clear()
1453 }
1454
1455 /// Creates a draining iterator that removes the specified range in the string
1456 /// and yields the removed chars.
1457 ///
1458 /// Note: The element range is removed even if the iterator is not
1459 /// consumed until the end.
1460 ///
1461 /// # Panics
1462 ///
1463 /// Panics if the starting point or end point do not lie on a [`char`]
1464 /// boundary, or if they're out of bounds.
1465 ///
1466 /// [`char`]: ../../std/primitive.char.html
1467 ///
1468 /// # Examples
1469 ///
1470 /// Basic usage:
1471 ///
1472 /// ```
1473 /// let mut s = String::from("α is alpha, β is beta");
1474 /// let beta_offset = s.find('β').unwrap_or(s.len());
1475 ///
1476 /// // Remove the range up until the β from the string
1477 /// let t: String = s.drain(..beta_offset).collect();
1478 /// assert_eq!(t, "α is alpha, ");
1479 /// assert_eq!(s, "β is beta");
1480 ///
1481 /// // A full range clears the string
1482 /// s.drain(..);
1483 /// assert_eq!(s, "");
1484 /// ```
1485 #[stable(feature = "drain", since = "1.6.0")]
1486 pub fn drain<R>(&mut self, range: R) -> Drain
1487 where R: RangeBounds<usize>
1488 {
1489 // Memory safety
1490 //
1491 // The String version of Drain does not have the memory safety issues
1492 // of the vector version. The data is just plain bytes.
1493 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1494 // the removal will not happen.
1495 let len = self.len();
1496 let start = match range.start_bound() {
1497 Included(&n) => n,
1498 Excluded(&n) => n + 1,
1499 Unbounded => 0,
1500 };
1501 let end = match range.end_bound() {
1502 Included(&n) => n + 1,
1503 Excluded(&n) => n,
1504 Unbounded => len,
1505 };
1506
1507 // Take out two simultaneous borrows. The &mut String won't be accessed
1508 // until iteration is over, in Drop.
1509 let self_ptr = self as *mut _;
1510 // slicing does the appropriate bounds checks
1511 let chars_iter = self[start..end].chars();
1512
1513 Drain {
1514 start,
1515 end,
1516 iter: chars_iter,
1517 string: self_ptr,
1518 }
1519 }
1520
1521 /// Removes the specified range in the string,
1522 /// and replaces it with the given string.
1523 /// The given string doesn't need to be the same length as the range.
1524 ///
1525 /// # Panics
1526 ///
1527 /// Panics if the starting point or end point do not lie on a [`char`]
1528 /// boundary, or if they're out of bounds.
1529 ///
1530 /// [`char`]: ../../std/primitive.char.html
1531 /// [`Vec::splice`]: ../../std/vec/struct.Vec.html#method.splice
1532 ///
1533 /// # Examples
1534 ///
1535 /// Basic usage:
1536 ///
1537 /// ```
1538 /// let mut s = String::from("α is alpha, β is beta");
1539 /// let beta_offset = s.find('β').unwrap_or(s.len());
1540 ///
1541 /// // Replace the range up until the β from the string
1542 /// s.replace_range(..beta_offset, "Α is capital alpha; ");
1543 /// assert_eq!(s, "Α is capital alpha; β is beta");
1544 /// ```
1545 #[stable(feature = "splice", since = "1.27.0")]
1546 pub fn replace_range<R>(&mut self, range: R, replace_with: &str)
1547 where R: RangeBounds<usize>
1548 {
1549 // Memory safety
1550 //
1551 // Replace_range does not have the memory safety issues of a vector Splice.
1552 // of the vector version. The data is just plain bytes.
1553
1554 match range.start_bound() {
1555 Included(&n) => assert!(self.is_char_boundary(n)),
1556 Excluded(&n) => assert!(self.is_char_boundary(n + 1)),
1557 Unbounded => {},
1558 };
1559 match range.end_bound() {
1560 Included(&n) => assert!(self.is_char_boundary(n + 1)),
1561 Excluded(&n) => assert!(self.is_char_boundary(n)),
1562 Unbounded => {},
1563 };
1564
1565 unsafe {
1566 self.as_mut_vec()
1567 }.splice(range, replace_with.bytes());
1568 }
1569
1570 /// Converts this `String` into a [`Box`]`<`[`str`]`>`.
1571 ///
1572 /// This will drop any excess capacity.
1573 ///
1574 /// [`Box`]: ../../std/boxed/struct.Box.html
1575 /// [`str`]: ../../std/primitive.str.html
1576 ///
1577 /// # Examples
1578 ///
1579 /// Basic usage:
1580 ///
1581 /// ```
1582 /// let s = String::from("hello");
1583 ///
1584 /// let b = s.into_boxed_str();
1585 /// ```
1586 #[stable(feature = "box_str", since = "1.4.0")]
1587 #[inline]
1588 pub fn into_boxed_str(self) -> Box<str> {
1589 let slice = self.vec.into_boxed_slice();
1590 unsafe { from_boxed_utf8_unchecked(slice) }
1591 }
1592 }
1593
1594 impl FromUtf8Error {
1595 /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
1596 ///
1597 /// # Examples
1598 ///
1599 /// Basic usage:
1600 ///
1601 /// ```
1602 /// // some invalid bytes, in a vector
1603 /// let bytes = vec![0, 159];
1604 ///
1605 /// let value = String::from_utf8(bytes);
1606 ///
1607 /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1608 /// ```
1609 #[stable(feature = "from_utf8_error_as_bytes", since = "1.26.0")]
1610 pub fn as_bytes(&self) -> &[u8] {
1611 &self.bytes[..]
1612 }
1613
1614 /// Returns the bytes that were attempted to convert to a `String`.
1615 ///
1616 /// This method is carefully constructed to avoid allocation. It will
1617 /// consume the error, moving out the bytes, so that a copy of the bytes
1618 /// does not need to be made.
1619 ///
1620 /// # Examples
1621 ///
1622 /// Basic usage:
1623 ///
1624 /// ```
1625 /// // some invalid bytes, in a vector
1626 /// let bytes = vec![0, 159];
1627 ///
1628 /// let value = String::from_utf8(bytes);
1629 ///
1630 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1631 /// ```
1632 #[stable(feature = "rust1", since = "1.0.0")]
1633 pub fn into_bytes(self) -> Vec<u8> {
1634 self.bytes
1635 }
1636
1637 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1638 ///
1639 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1640 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1641 /// an analogue to `FromUtf8Error`. See its documentation for more details
1642 /// on using it.
1643 ///
1644 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
1645 /// [`std::str`]: ../../std/str/index.html
1646 /// [`u8`]: ../../std/primitive.u8.html
1647 /// [`&str`]: ../../std/primitive.str.html
1648 ///
1649 /// # Examples
1650 ///
1651 /// Basic usage:
1652 ///
1653 /// ```
1654 /// // some invalid bytes, in a vector
1655 /// let bytes = vec![0, 159];
1656 ///
1657 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1658 ///
1659 /// // the first byte is invalid here
1660 /// assert_eq!(1, error.valid_up_to());
1661 /// ```
1662 #[stable(feature = "rust1", since = "1.0.0")]
1663 pub fn utf8_error(&self) -> Utf8Error {
1664 self.error
1665 }
1666 }
1667
1668 #[stable(feature = "rust1", since = "1.0.0")]
1669 impl fmt::Display for FromUtf8Error {
1670 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1671 fmt::Display::fmt(&self.error, f)
1672 }
1673 }
1674
1675 #[stable(feature = "rust1", since = "1.0.0")]
1676 impl fmt::Display for FromUtf16Error {
1677 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1678 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1679 }
1680 }
1681
1682 #[stable(feature = "rust1", since = "1.0.0")]
1683 impl Clone for String {
1684 fn clone(&self) -> Self {
1685 String { vec: self.vec.clone() }
1686 }
1687
1688 fn clone_from(&mut self, source: &Self) {
1689 self.vec.clone_from(&source.vec);
1690 }
1691 }
1692
1693 #[stable(feature = "rust1", since = "1.0.0")]
1694 impl FromIterator<char> for String {
1695 fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1696 let mut buf = String::new();
1697 buf.extend(iter);
1698 buf
1699 }
1700 }
1701
1702 #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
1703 impl<'a> FromIterator<&'a char> for String {
1704 fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
1705 let mut buf = String::new();
1706 buf.extend(iter);
1707 buf
1708 }
1709 }
1710
1711 #[stable(feature = "rust1", since = "1.0.0")]
1712 impl<'a> FromIterator<&'a str> for String {
1713 fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1714 let mut buf = String::new();
1715 buf.extend(iter);
1716 buf
1717 }
1718 }
1719
1720 #[stable(feature = "extend_string", since = "1.4.0")]
1721 impl FromIterator<String> for String {
1722 fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1723 let mut buf = String::new();
1724 buf.extend(iter);
1725 buf
1726 }
1727 }
1728
1729 #[stable(feature = "herd_cows", since = "1.19.0")]
1730 impl<'a> FromIterator<Cow<'a, str>> for String {
1731 fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> String {
1732 let mut buf = String::new();
1733 buf.extend(iter);
1734 buf
1735 }
1736 }
1737
1738 #[stable(feature = "rust1", since = "1.0.0")]
1739 impl Extend<char> for String {
1740 fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1741 let iterator = iter.into_iter();
1742 let (lower_bound, _) = iterator.size_hint();
1743 self.reserve(lower_bound);
1744 for ch in iterator {
1745 self.push(ch)
1746 }
1747 }
1748 }
1749
1750 #[stable(feature = "extend_ref", since = "1.2.0")]
1751 impl<'a> Extend<&'a char> for String {
1752 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1753 self.extend(iter.into_iter().cloned());
1754 }
1755 }
1756
1757 #[stable(feature = "rust1", since = "1.0.0")]
1758 impl<'a> Extend<&'a str> for String {
1759 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1760 for s in iter {
1761 self.push_str(s)
1762 }
1763 }
1764 }
1765
1766 #[stable(feature = "extend_string", since = "1.4.0")]
1767 impl Extend<String> for String {
1768 fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1769 for s in iter {
1770 self.push_str(&s)
1771 }
1772 }
1773 }
1774
1775 #[stable(feature = "herd_cows", since = "1.19.0")]
1776 impl<'a> Extend<Cow<'a, str>> for String {
1777 fn extend<I: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: I) {
1778 for s in iter {
1779 self.push_str(&s)
1780 }
1781 }
1782 }
1783
1784 /// A convenience impl that delegates to the impl for `&str`
1785 #[unstable(feature = "pattern",
1786 reason = "API not fully fleshed out and ready to be stabilized",
1787 issue = "27721")]
1788 impl<'a, 'b> Pattern<'a> for &'b String {
1789 type Searcher = <&'b str as Pattern<'a>>::Searcher;
1790
1791 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1792 self[..].into_searcher(haystack)
1793 }
1794
1795 #[inline]
1796 fn is_contained_in(self, haystack: &'a str) -> bool {
1797 self[..].is_contained_in(haystack)
1798 }
1799
1800 #[inline]
1801 fn is_prefix_of(self, haystack: &'a str) -> bool {
1802 self[..].is_prefix_of(haystack)
1803 }
1804 }
1805
1806 #[stable(feature = "rust1", since = "1.0.0")]
1807 impl PartialEq for String {
1808 #[inline]
1809 fn eq(&self, other: &String) -> bool {
1810 PartialEq::eq(&self[..], &other[..])
1811 }
1812 #[inline]
1813 fn ne(&self, other: &String) -> bool {
1814 PartialEq::ne(&self[..], &other[..])
1815 }
1816 }
1817
1818 macro_rules! impl_eq {
1819 ($lhs:ty, $rhs: ty) => {
1820 #[stable(feature = "rust1", since = "1.0.0")]
1821 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1822 #[inline]
1823 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1824 #[inline]
1825 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1826 }
1827
1828 #[stable(feature = "rust1", since = "1.0.0")]
1829 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1830 #[inline]
1831 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1832 #[inline]
1833 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1834 }
1835
1836 }
1837 }
1838
1839 impl_eq! { String, str }
1840 impl_eq! { String, &'a str }
1841 impl_eq! { Cow<'a, str>, str }
1842 impl_eq! { Cow<'a, str>, &'b str }
1843 impl_eq! { Cow<'a, str>, String }
1844
1845 #[stable(feature = "rust1", since = "1.0.0")]
1846 impl Default for String {
1847 /// Creates an empty `String`.
1848 #[inline]
1849 fn default() -> String {
1850 String::new()
1851 }
1852 }
1853
1854 #[stable(feature = "rust1", since = "1.0.0")]
1855 impl fmt::Display for String {
1856 #[inline]
1857 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1858 fmt::Display::fmt(&**self, f)
1859 }
1860 }
1861
1862 #[stable(feature = "rust1", since = "1.0.0")]
1863 impl fmt::Debug for String {
1864 #[inline]
1865 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1866 fmt::Debug::fmt(&**self, f)
1867 }
1868 }
1869
1870 #[stable(feature = "rust1", since = "1.0.0")]
1871 impl hash::Hash for String {
1872 #[inline]
1873 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1874 (**self).hash(hasher)
1875 }
1876 }
1877
1878 /// Implements the `+` operator for concatenating two strings.
1879 ///
1880 /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
1881 /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
1882 /// every operation, which would lead to `O(n^2)` running time when building an `n`-byte string by
1883 /// repeated concatenation.
1884 ///
1885 /// The string on the right-hand side is only borrowed; its contents are copied into the returned
1886 /// `String`.
1887 ///
1888 /// # Examples
1889 ///
1890 /// Concatenating two `String`s takes the first by value and borrows the second:
1891 ///
1892 /// ```
1893 /// let a = String::from("hello");
1894 /// let b = String::from(" world");
1895 /// let c = a + &b;
1896 /// // `a` is moved and can no longer be used here.
1897 /// ```
1898 ///
1899 /// If you want to keep using the first `String`, you can clone it and append to the clone instead:
1900 ///
1901 /// ```
1902 /// let a = String::from("hello");
1903 /// let b = String::from(" world");
1904 /// let c = a.clone() + &b;
1905 /// // `a` is still valid here.
1906 /// ```
1907 ///
1908 /// Concatenating `&str` slices can be done by converting the first to a `String`:
1909 ///
1910 /// ```
1911 /// let a = "hello";
1912 /// let b = " world";
1913 /// let c = a.to_string() + b;
1914 /// ```
1915 #[stable(feature = "rust1", since = "1.0.0")]
1916 impl<'a> Add<&'a str> for String {
1917 type Output = String;
1918
1919 #[inline]
1920 fn add(mut self, other: &str) -> String {
1921 self.push_str(other);
1922 self
1923 }
1924 }
1925
1926 /// Implements the `+=` operator for appending to a `String`.
1927 ///
1928 /// This has the same behavior as the [`push_str`] method.
1929 ///
1930 /// [`push_str`]: struct.String.html#method.push_str
1931 #[stable(feature = "stringaddassign", since = "1.12.0")]
1932 impl<'a> AddAssign<&'a str> for String {
1933 #[inline]
1934 fn add_assign(&mut self, other: &str) {
1935 self.push_str(other);
1936 }
1937 }
1938
1939 #[stable(feature = "rust1", since = "1.0.0")]
1940 impl ops::Index<ops::Range<usize>> for String {
1941 type Output = str;
1942
1943 #[inline]
1944 fn index(&self, index: ops::Range<usize>) -> &str {
1945 &self[..][index]
1946 }
1947 }
1948 #[stable(feature = "rust1", since = "1.0.0")]
1949 impl ops::Index<ops::RangeTo<usize>> for String {
1950 type Output = str;
1951
1952 #[inline]
1953 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1954 &self[..][index]
1955 }
1956 }
1957 #[stable(feature = "rust1", since = "1.0.0")]
1958 impl ops::Index<ops::RangeFrom<usize>> for String {
1959 type Output = str;
1960
1961 #[inline]
1962 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1963 &self[..][index]
1964 }
1965 }
1966 #[stable(feature = "rust1", since = "1.0.0")]
1967 impl ops::Index<ops::RangeFull> for String {
1968 type Output = str;
1969
1970 #[inline]
1971 fn index(&self, _index: ops::RangeFull) -> &str {
1972 unsafe { str::from_utf8_unchecked(&self.vec) }
1973 }
1974 }
1975 #[stable(feature = "inclusive_range", since = "1.26.0")]
1976 impl ops::Index<ops::RangeInclusive<usize>> for String {
1977 type Output = str;
1978
1979 #[inline]
1980 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1981 Index::index(&**self, index)
1982 }
1983 }
1984 #[stable(feature = "inclusive_range", since = "1.26.0")]
1985 impl ops::Index<ops::RangeToInclusive<usize>> for String {
1986 type Output = str;
1987
1988 #[inline]
1989 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1990 Index::index(&**self, index)
1991 }
1992 }
1993
1994 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1995 impl ops::IndexMut<ops::Range<usize>> for String {
1996 #[inline]
1997 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1998 &mut self[..][index]
1999 }
2000 }
2001 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2002 impl ops::IndexMut<ops::RangeTo<usize>> for String {
2003 #[inline]
2004 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
2005 &mut self[..][index]
2006 }
2007 }
2008 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2009 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
2010 #[inline]
2011 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
2012 &mut self[..][index]
2013 }
2014 }
2015 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2016 impl ops::IndexMut<ops::RangeFull> for String {
2017 #[inline]
2018 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
2019 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2020 }
2021 }
2022 #[stable(feature = "inclusive_range", since = "1.26.0")]
2023 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
2024 #[inline]
2025 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
2026 IndexMut::index_mut(&mut **self, index)
2027 }
2028 }
2029 #[stable(feature = "inclusive_range", since = "1.26.0")]
2030 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
2031 #[inline]
2032 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
2033 IndexMut::index_mut(&mut **self, index)
2034 }
2035 }
2036
2037 #[stable(feature = "rust1", since = "1.0.0")]
2038 impl ops::Deref for String {
2039 type Target = str;
2040
2041 #[inline]
2042 fn deref(&self) -> &str {
2043 unsafe { str::from_utf8_unchecked(&self.vec) }
2044 }
2045 }
2046
2047 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2048 impl ops::DerefMut for String {
2049 #[inline]
2050 fn deref_mut(&mut self) -> &mut str {
2051 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2052 }
2053 }
2054
2055 /// An error when parsing a `String`.
2056 ///
2057 /// This `enum` is slightly awkward: it will never actually exist. This error is
2058 /// part of the type signature of the implementation of [`FromStr`] on
2059 /// [`String`]. The return type of [`from_str`], requires that an error be
2060 /// defined, but, given that a [`String`] can always be made into a new
2061 /// [`String`] without error, this type will never actually be returned. As
2062 /// such, it is only here to satisfy said signature, and is useless otherwise.
2063 ///
2064 /// [`FromStr`]: ../../std/str/trait.FromStr.html
2065 /// [`String`]: struct.String.html
2066 /// [`from_str`]: ../../std/str/trait.FromStr.html#tymethod.from_str
2067 #[stable(feature = "str_parse_error", since = "1.5.0")]
2068 #[derive(Copy)]
2069 pub enum ParseError {}
2070
2071 #[stable(feature = "rust1", since = "1.0.0")]
2072 impl FromStr for String {
2073 type Err = ParseError;
2074 #[inline]
2075 fn from_str(s: &str) -> Result<String, ParseError> {
2076 Ok(String::from(s))
2077 }
2078 }
2079
2080 #[stable(feature = "str_parse_error", since = "1.5.0")]
2081 impl Clone for ParseError {
2082 fn clone(&self) -> ParseError {
2083 match *self {}
2084 }
2085 }
2086
2087 #[stable(feature = "str_parse_error", since = "1.5.0")]
2088 impl fmt::Debug for ParseError {
2089 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
2090 match *self {}
2091 }
2092 }
2093
2094 #[stable(feature = "str_parse_error2", since = "1.8.0")]
2095 impl fmt::Display for ParseError {
2096 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
2097 match *self {}
2098 }
2099 }
2100
2101 #[stable(feature = "str_parse_error", since = "1.5.0")]
2102 impl PartialEq for ParseError {
2103 fn eq(&self, _: &ParseError) -> bool {
2104 match *self {}
2105 }
2106 }
2107
2108 #[stable(feature = "str_parse_error", since = "1.5.0")]
2109 impl Eq for ParseError {}
2110
2111 /// A trait for converting a value to a `String`.
2112 ///
2113 /// This trait is automatically implemented for any type which implements the
2114 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
2115 /// [`Display`] should be implemented instead, and you get the `ToString`
2116 /// implementation for free.
2117 ///
2118 /// [`Display`]: ../../std/fmt/trait.Display.html
2119 #[stable(feature = "rust1", since = "1.0.0")]
2120 pub trait ToString {
2121 /// Converts the given value to a `String`.
2122 ///
2123 /// # Examples
2124 ///
2125 /// Basic usage:
2126 ///
2127 /// ```
2128 /// let i = 5;
2129 /// let five = String::from("5");
2130 ///
2131 /// assert_eq!(five, i.to_string());
2132 /// ```
2133 #[rustc_conversion_suggestion]
2134 #[stable(feature = "rust1", since = "1.0.0")]
2135 fn to_string(&self) -> String;
2136 }
2137
2138 /// # Panics
2139 ///
2140 /// In this implementation, the `to_string` method panics
2141 /// if the `Display` implementation returns an error.
2142 /// This indicates an incorrect `Display` implementation
2143 /// since `fmt::Write for String` never returns an error itself.
2144 #[stable(feature = "rust1", since = "1.0.0")]
2145 impl<T: fmt::Display + ?Sized> ToString for T {
2146 #[inline]
2147 default fn to_string(&self) -> String {
2148 use core::fmt::Write;
2149 let mut buf = String::new();
2150 buf.write_fmt(format_args!("{}", self))
2151 .expect("a Display implementation return an error unexpectedly");
2152 buf.shrink_to_fit();
2153 buf
2154 }
2155 }
2156
2157 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
2158 impl ToString for str {
2159 #[inline]
2160 fn to_string(&self) -> String {
2161 String::from(self)
2162 }
2163 }
2164
2165 #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")]
2166 impl<'a> ToString for Cow<'a, str> {
2167 #[inline]
2168 fn to_string(&self) -> String {
2169 self[..].to_owned()
2170 }
2171 }
2172
2173 #[stable(feature = "string_to_string_specialization", since = "1.17.0")]
2174 impl ToString for String {
2175 #[inline]
2176 fn to_string(&self) -> String {
2177 self.to_owned()
2178 }
2179 }
2180
2181 #[stable(feature = "rust1", since = "1.0.0")]
2182 impl AsRef<str> for String {
2183 #[inline]
2184 fn as_ref(&self) -> &str {
2185 self
2186 }
2187 }
2188
2189 #[stable(feature = "rust1", since = "1.0.0")]
2190 impl AsRef<[u8]> for String {
2191 #[inline]
2192 fn as_ref(&self) -> &[u8] {
2193 self.as_bytes()
2194 }
2195 }
2196
2197 #[stable(feature = "rust1", since = "1.0.0")]
2198 impl<'a> From<&'a str> for String {
2199 fn from(s: &'a str) -> String {
2200 s.to_owned()
2201 }
2202 }
2203
2204 // note: test pulls in libstd, which causes errors here
2205 #[cfg(not(test))]
2206 #[stable(feature = "string_from_box", since = "1.18.0")]
2207 impl From<Box<str>> for String {
2208 fn from(s: Box<str>) -> String {
2209 s.into_string()
2210 }
2211 }
2212
2213 #[stable(feature = "box_from_str", since = "1.20.0")]
2214 impl From<String> for Box<str> {
2215 fn from(s: String) -> Box<str> {
2216 s.into_boxed_str()
2217 }
2218 }
2219
2220 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
2221 impl<'a> From<Cow<'a, str>> for String {
2222 fn from(s: Cow<'a, str>) -> String {
2223 s.into_owned()
2224 }
2225 }
2226
2227 #[stable(feature = "rust1", since = "1.0.0")]
2228 impl<'a> From<&'a str> for Cow<'a, str> {
2229 #[inline]
2230 fn from(s: &'a str) -> Cow<'a, str> {
2231 Cow::Borrowed(s)
2232 }
2233 }
2234
2235 #[stable(feature = "rust1", since = "1.0.0")]
2236 impl<'a> From<String> for Cow<'a, str> {
2237 #[inline]
2238 fn from(s: String) -> Cow<'a, str> {
2239 Cow::Owned(s)
2240 }
2241 }
2242
2243 #[stable(feature = "cow_from_string_ref", since = "1.28.0")]
2244 impl<'a> From<&'a String> for Cow<'a, str> {
2245 #[inline]
2246 fn from(s: &'a String) -> Cow<'a, str> {
2247 Cow::Borrowed(s.as_str())
2248 }
2249 }
2250
2251 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2252 impl<'a> FromIterator<char> for Cow<'a, str> {
2253 fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
2254 Cow::Owned(FromIterator::from_iter(it))
2255 }
2256 }
2257
2258 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2259 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
2260 fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
2261 Cow::Owned(FromIterator::from_iter(it))
2262 }
2263 }
2264
2265 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2266 impl<'a> FromIterator<String> for Cow<'a, str> {
2267 fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
2268 Cow::Owned(FromIterator::from_iter(it))
2269 }
2270 }
2271
2272 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
2273 impl From<String> for Vec<u8> {
2274 fn from(string: String) -> Vec<u8> {
2275 string.into_bytes()
2276 }
2277 }
2278
2279 #[stable(feature = "rust1", since = "1.0.0")]
2280 impl fmt::Write for String {
2281 #[inline]
2282 fn write_str(&mut self, s: &str) -> fmt::Result {
2283 self.push_str(s);
2284 Ok(())
2285 }
2286
2287 #[inline]
2288 fn write_char(&mut self, c: char) -> fmt::Result {
2289 self.push(c);
2290 Ok(())
2291 }
2292 }
2293
2294 /// A draining iterator for `String`.
2295 ///
2296 /// This struct is created by the [`drain`] method on [`String`]. See its
2297 /// documentation for more.
2298 ///
2299 /// [`drain`]: struct.String.html#method.drain
2300 /// [`String`]: struct.String.html
2301 #[stable(feature = "drain", since = "1.6.0")]
2302 pub struct Drain<'a> {
2303 /// Will be used as &'a mut String in the destructor
2304 string: *mut String,
2305 /// Start of part to remove
2306 start: usize,
2307 /// End of part to remove
2308 end: usize,
2309 /// Current remaining range to remove
2310 iter: Chars<'a>,
2311 }
2312
2313 #[stable(feature = "collection_debug", since = "1.17.0")]
2314 impl<'a> fmt::Debug for Drain<'a> {
2315 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2316 f.pad("Drain { .. }")
2317 }
2318 }
2319
2320 #[stable(feature = "drain", since = "1.6.0")]
2321 unsafe impl<'a> Sync for Drain<'a> {}
2322 #[stable(feature = "drain", since = "1.6.0")]
2323 unsafe impl<'a> Send for Drain<'a> {}
2324
2325 #[stable(feature = "drain", since = "1.6.0")]
2326 impl<'a> Drop for Drain<'a> {
2327 fn drop(&mut self) {
2328 unsafe {
2329 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2330 // panic code being inserted again.
2331 let self_vec = (*self.string).as_mut_vec();
2332 if self.start <= self.end && self.end <= self_vec.len() {
2333 self_vec.drain(self.start..self.end);
2334 }
2335 }
2336 }
2337 }
2338
2339 #[stable(feature = "drain", since = "1.6.0")]
2340 impl<'a> Iterator for Drain<'a> {
2341 type Item = char;
2342
2343 #[inline]
2344 fn next(&mut self) -> Option<char> {
2345 self.iter.next()
2346 }
2347
2348 fn size_hint(&self) -> (usize, Option<usize>) {
2349 self.iter.size_hint()
2350 }
2351 }
2352
2353 #[stable(feature = "drain", since = "1.6.0")]
2354 impl<'a> DoubleEndedIterator for Drain<'a> {
2355 #[inline]
2356 fn next_back(&mut self) -> Option<char> {
2357 self.iter.next_back()
2358 }
2359 }
2360
2361 #[stable(feature = "fused", since = "1.26.0")]
2362 impl<'a> FusedIterator for Drain<'a> {}