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