]>
Commit | Line | Data |
---|---|---|
29967ef6 | 1 | //! A UTF-8–encoded, growable string. |
92a42be0 | 2 | //! |
29967ef6 XL |
3 | //! This module contains the [`String`] type, the [`ToString`] trait for |
4 | //! converting to strings, and several error types that may result from | |
5 | //! working with [`String`]s. | |
92a42be0 | 6 | //! |
9cc50fc6 SL |
7 | //! # Examples |
8 | //! | |
c30ab7b3 | 9 | //! There are multiple ways to create a new [`String`] from a string literal: |
9cc50fc6 | 10 | //! |
c30ab7b3 | 11 | //! ``` |
9cc50fc6 SL |
12 | //! let s = "Hello".to_string(); |
13 | //! | |
14 | //! let s = String::from("world"); | |
15 | //! let s: String = "also this".into(); | |
16 | //! ``` | |
17 | //! | |
c30ab7b3 | 18 | //! You can create a new [`String`] from an existing one by concatenating with |
9cc50fc6 SL |
19 | //! `+`: |
20 | //! | |
c30ab7b3 | 21 | //! ``` |
9cc50fc6 SL |
22 | //! let s = "Hello".to_string(); |
23 | //! | |
24 | //! let message = s + " world!"; | |
25 | //! ``` | |
26 | //! | |
3b2f2976 | 27 | //! If you have a vector of valid UTF-8 bytes, you can make a [`String`] out of |
9cc50fc6 SL |
28 | //! it. You can do the reverse too. |
29 | //! | |
c30ab7b3 | 30 | //! ``` |
9cc50fc6 SL |
31 | //! let sparkle_heart = vec![240, 159, 146, 150]; |
32 | //! | |
33 | //! // We know these bytes are valid, so we'll use `unwrap()`. | |
34 | //! let sparkle_heart = String::from_utf8(sparkle_heart).unwrap(); | |
35 | //! | |
36 | //! assert_eq!("💖", sparkle_heart); | |
37 | //! | |
38 | //! let bytes = sparkle_heart.into_bytes(); | |
39 | //! | |
40 | //! assert_eq!(bytes, [240, 159, 146, 150]); | |
41 | //! ``` | |
1a4d82fc | 42 | |
85aaf69f | 43 | #![stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 44 | |
17df50a5 | 45 | #[cfg(not(no_global_oom_handling))] |
83c7162d | 46 | use core::char::{decode_utf16, REPLACEMENT_CHARACTER}; |
f2b60f7d | 47 | use core::error::Error; |
1a4d82fc JJ |
48 | use core::fmt; |
49 | use core::hash; | |
064997fb | 50 | use core::iter::FusedIterator; |
17df50a5 | 51 | #[cfg(not(no_global_oom_handling))] |
064997fb | 52 | use core::iter::{from_fn, FromIterator}; |
17df50a5 XL |
53 | #[cfg(not(no_global_oom_handling))] |
54 | use core::ops::Add; | |
55 | #[cfg(not(no_global_oom_handling))] | |
56 | use core::ops::AddAssign; | |
57 | #[cfg(not(no_global_oom_handling))] | |
9fa01778 | 58 | use core::ops::Bound::{Excluded, Included, Unbounded}; |
17df50a5 | 59 | use core::ops::{self, Index, IndexMut, Range, RangeBounds}; |
1a4d82fc | 60 | use core::ptr; |
6a06907d | 61 | use core::slice; |
17df50a5 | 62 | use core::str::pattern::Pattern; |
f2b60f7d FG |
63 | #[cfg(not(no_global_oom_handling))] |
64 | use core::str::Utf8Chunks; | |
1a4d82fc | 65 | |
17df50a5 | 66 | #[cfg(not(no_global_oom_handling))] |
9fa01778 | 67 | use crate::borrow::{Cow, ToOwned}; |
9fa01778 | 68 | use crate::boxed::Box; |
dfeec247 | 69 | use crate::collections::TryReserveError; |
2b03887a | 70 | use crate::str::{self, from_utf8_unchecked_mut, Chars, Utf8Error}; |
17df50a5 XL |
71 | #[cfg(not(no_global_oom_handling))] |
72 | use crate::str::{from_boxed_utf8_unchecked, FromStr}; | |
9fa01778 | 73 | use crate::vec::Vec; |
1a4d82fc | 74 | |
29967ef6 | 75 | /// A UTF-8–encoded, growable string. |
92a42be0 SL |
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 | /// | |
92a42be0 SL |
81 | /// # Examples |
82 | /// | |
c295e0f8 | 83 | /// You can create a `String` from [a literal string][`&str`] with [`String::from`]: |
3dfed10e XL |
84 | /// |
85 | /// [`String::from`]: From::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 | /// | |
3dfed10e XL |
101 | /// [`push`]: String::push |
102 | /// [`push_str`]: String::push_str | |
92a42be0 SL |
103 | /// |
104 | /// If you have a vector of UTF-8 bytes, you can create a `String` from it with | |
cc61c64b | 105 | /// the [`from_utf8`] method: |
92a42be0 SL |
106 | /// |
107 | /// ``` | |
108 | /// // some bytes, in a vector | |
109 | /// let sparkle_heart = vec![240, 159, 146, 150]; | |
110 | /// | |
111 | /// // We know these bytes are valid, so we'll use `unwrap()`. | |
112 | /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap(); | |
113 | /// | |
114 | /// assert_eq!("💖", sparkle_heart); | |
115 | /// ``` | |
116 | /// | |
3dfed10e | 117 | /// [`from_utf8`]: String::from_utf8 |
92a42be0 SL |
118 | /// |
119 | /// # UTF-8 | |
120 | /// | |
04454e1e FG |
121 | /// `String`s are always valid UTF-8. If you need a non-UTF-8 string, consider |
122 | /// [`OsString`]. It is similar, but without the UTF-8 constraint. Because UTF-8 | |
123 | /// is a variable width encoding, `String`s are typically smaller than an array of | |
124 | /// the same `chars`: | |
125 | /// | |
126 | /// ``` | |
127 | /// use std::mem; | |
128 | /// | |
129 | /// // `s` is ASCII which represents each `char` as one byte | |
130 | /// let s = "hello"; | |
131 | /// assert_eq!(s.len(), 5); | |
132 | /// | |
133 | /// // A `char` array with the same contents would be longer because | |
134 | /// // every `char` is four bytes | |
135 | /// let s = ['h', 'e', 'l', 'l', 'o']; | |
136 | /// let size: usize = s.into_iter().map(|c| mem::size_of_val(&c)).sum(); | |
137 | /// assert_eq!(size, 20); | |
138 | /// | |
139 | /// // However, for non-ASCII strings, the difference will be smaller | |
140 | /// // and sometimes they are the same | |
141 | /// let s = "💖💖💖💖💖"; | |
142 | /// assert_eq!(s.len(), 20); | |
143 | /// | |
144 | /// let s = ['💖', '💖', '💖', '💖', '💖']; | |
145 | /// let size: usize = s.into_iter().map(|c| mem::size_of_val(&c)).sum(); | |
146 | /// assert_eq!(size, 20); | |
147 | /// ``` | |
148 | /// | |
149 | /// This raises interesting questions as to how `s[i]` should work. | |
150 | /// What should `i` be here? Several options include byte indices and | |
151 | /// `char` indices but, because of UTF-8 encoding, only byte indices | |
152 | /// would provide constant time indexing. Getting the `i`th `char`, for | |
153 | /// example, is available using [`chars`]: | |
154 | /// | |
155 | /// ``` | |
156 | /// let s = "hello"; | |
157 | /// let third_character = s.chars().nth(2); | |
158 | /// assert_eq!(third_character, Some('l')); | |
159 | /// | |
160 | /// let s = "💖💖💖💖💖"; | |
161 | /// let third_character = s.chars().nth(2); | |
162 | /// assert_eq!(third_character, Some('💖')); | |
163 | /// ``` | |
164 | /// | |
165 | /// Next, what should `s[i]` return? Because indexing returns a reference | |
166 | /// to underlying data it could be `&u8`, `&[u8]`, or something else similar. | |
167 | /// Since we're only providing one index, `&u8` makes the most sense but that | |
168 | /// might not be what the user expects and can be explicitly achieved with | |
169 | /// [`as_bytes()`]: | |
170 | /// | |
171 | /// ``` | |
172 | /// // The first byte is 104 - the byte value of `'h'` | |
173 | /// let s = "hello"; | |
174 | /// assert_eq!(s.as_bytes()[0], 104); | |
175 | /// // or | |
176 | /// assert_eq!(s.as_bytes()[0], b'h'); | |
177 | /// | |
178 | /// // The first byte is 240 which isn't obviously useful | |
179 | /// let s = "💖💖💖💖💖"; | |
180 | /// assert_eq!(s.as_bytes()[0], 240); | |
181 | /// ``` | |
182 | /// | |
183 | /// Due to these ambiguities/restrictions, indexing with a `usize` is simply | |
184 | /// forbidden: | |
92a42be0 | 185 | /// |
041b39d2 | 186 | /// ```compile_fail,E0277 |
92a42be0 SL |
187 | /// let s = "hello"; |
188 | /// | |
04454e1e FG |
189 | /// // The following will not compile! |
190 | /// println!("The first letter of s is {}", s[0]); | |
92a42be0 SL |
191 | /// ``` |
192 | /// | |
04454e1e FG |
193 | /// It is more clear, however, how `&s[i..j]` should work (that is, |
194 | /// indexing with a range). It should accept byte indices (to be constant-time) | |
195 | /// and return a `&str` which is UTF-8 encoded. This is also called "string slicing". | |
196 | /// Note this will panic if the byte indices provided are not character | |
197 | /// boundaries - see [`is_char_boundary`] for more details. See the implementations | |
198 | /// for [`SliceIndex<str>`] for more details on string slicing. For a non-panicking | |
199 | /// version of string slicing, see [`get`]. | |
200 | /// | |
c295e0f8 | 201 | /// [`OsString`]: ../../std/ffi/struct.OsString.html "ffi::OsString" |
04454e1e FG |
202 | /// [`SliceIndex<str>`]: core::slice::SliceIndex |
203 | /// [`as_bytes()`]: str::as_bytes | |
204 | /// [`get`]: str::get | |
205 | /// [`is_char_boundary`]: str::is_char_boundary | |
92a42be0 | 206 | /// |
04454e1e FG |
207 | /// The [`bytes`] and [`chars`] methods return iterators over the bytes and |
208 | /// codepoints of the string, respectively. To iterate over codepoints along | |
209 | /// with byte indices, use [`char_indices`]. | |
92a42be0 | 210 | /// |
3dfed10e XL |
211 | /// [`bytes`]: str::bytes |
212 | /// [`chars`]: str::chars | |
04454e1e | 213 | /// [`char_indices`]: str::char_indices |
92a42be0 SL |
214 | /// |
215 | /// # Deref | |
216 | /// | |
c295e0f8 | 217 | /// `String` implements <code>[Deref]<Target = [str]></code>, and so inherits all of [`str`]'s |
3b2f2976 | 218 | /// methods. In addition, this means that you can pass a `String` to a |
92a42be0 SL |
219 | /// function which takes a [`&str`] by using an ampersand (`&`): |
220 | /// | |
221 | /// ``` | |
222 | /// fn takes_str(s: &str) { } | |
223 | /// | |
224 | /// let s = String::from("Hello"); | |
225 | /// | |
226 | /// takes_str(&s); | |
227 | /// ``` | |
228 | /// | |
92a42be0 SL |
229 | /// This will create a [`&str`] from the `String` and pass it in. This |
230 | /// conversion is very inexpensive, and so generally, functions will accept | |
3b2f2976 XL |
231 | /// [`&str`]s as arguments unless they need a `String` for some specific |
232 | /// reason. | |
233 | /// | |
234 | /// In certain cases Rust doesn't have enough information to make this | |
235 | /// conversion, known as [`Deref`] coercion. In the following example a string | |
236 | /// slice [`&'a str`][`&str`] implements the trait `TraitExample`, and the function | |
237 | /// `example_func` takes anything that implements the trait. In this case Rust | |
238 | /// would need to make two implicit conversions, which Rust doesn't have the | |
239 | /// means to do. For that reason, the following example will not compile. | |
240 | /// | |
241 | /// ```compile_fail,E0277 | |
242 | /// trait TraitExample {} | |
243 | /// | |
244 | /// impl<'a> TraitExample for &'a str {} | |
92a42be0 | 245 | /// |
3b2f2976 XL |
246 | /// fn example_func<A: TraitExample>(example_arg: A) {} |
247 | /// | |
e74abb32 XL |
248 | /// let example_string = String::from("example_string"); |
249 | /// example_func(&example_string); | |
3b2f2976 XL |
250 | /// ``` |
251 | /// | |
252 | /// There are two options that would work instead. The first would be to | |
253 | /// change the line `example_func(&example_string);` to | |
254 | /// `example_func(example_string.as_str());`, using the method [`as_str()`] | |
255 | /// to explicitly extract the string slice containing the string. The second | |
256 | /// way changes `example_func(&example_string);` to | |
257 | /// `example_func(&*example_string);`. In this case we are dereferencing a | |
c295e0f8 | 258 | /// `String` to a [`str`], then referencing the [`str`] back to |
3b2f2976 XL |
259 | /// [`&str`]. The second way is more idiomatic, however both work to do the |
260 | /// conversion explicitly rather than relying on the implicit conversion. | |
92a42be0 SL |
261 | /// |
262 | /// # Representation | |
263 | /// | |
264 | /// A `String` is made up of three components: a pointer to some bytes, a | |
265 | /// length, and a capacity. The pointer points to an internal buffer `String` | |
266 | /// uses to store its data. The length is the number of bytes currently stored | |
267 | /// in the buffer, and the capacity is the size of the buffer in bytes. As such, | |
268 | /// the length will always be less than or equal to the capacity. | |
269 | /// | |
270 | /// This buffer is always stored on the heap. | |
271 | /// | |
cc61c64b | 272 | /// You can look at these with the [`as_ptr`], [`len`], and [`capacity`] |
92a42be0 SL |
273 | /// methods: |
274 | /// | |
275 | /// ``` | |
276 | /// use std::mem; | |
277 | /// | |
278 | /// let story = String::from("Once upon a time..."); | |
279 | /// | |
e74abb32 XL |
280 | // FIXME Update this when vec_into_raw_parts is stabilized |
281 | /// // Prevent automatically dropping the String's data | |
282 | /// let mut story = mem::ManuallyDrop::new(story); | |
283 | /// | |
284 | /// let ptr = story.as_mut_ptr(); | |
92a42be0 SL |
285 | /// let len = story.len(); |
286 | /// let capacity = story.capacity(); | |
287 | /// | |
a7813a04 | 288 | /// // story has nineteen bytes |
92a42be0 SL |
289 | /// assert_eq!(19, len); |
290 | /// | |
92a42be0 | 291 | /// // We can re-build a String out of ptr, len, and capacity. This is all |
7453a54e | 292 | /// // unsafe because we are responsible for making sure the components are |
92a42be0 | 293 | /// // valid: |
e74abb32 | 294 | /// let s = unsafe { String::from_raw_parts(ptr, len, capacity) } ; |
92a42be0 SL |
295 | /// |
296 | /// assert_eq!(String::from("Once upon a time..."), s); | |
297 | /// ``` | |
298 | /// | |
3dfed10e XL |
299 | /// [`as_ptr`]: str::as_ptr |
300 | /// [`len`]: String::len | |
301 | /// [`capacity`]: String::capacity | |
92a42be0 SL |
302 | /// |
303 | /// If a `String` has enough capacity, adding elements to it will not | |
304 | /// re-allocate. For example, consider this program: | |
305 | /// | |
306 | /// ``` | |
307 | /// let mut s = String::new(); | |
308 | /// | |
309 | /// println!("{}", s.capacity()); | |
310 | /// | |
311 | /// for _ in 0..5 { | |
312 | /// s.push_str("hello"); | |
313 | /// println!("{}", s.capacity()); | |
314 | /// } | |
315 | /// ``` | |
316 | /// | |
317 | /// This will output the following: | |
318 | /// | |
319 | /// ```text | |
320 | /// 0 | |
064997fb FG |
321 | /// 8 |
322 | /// 16 | |
323 | /// 16 | |
324 | /// 32 | |
325 | /// 32 | |
92a42be0 SL |
326 | /// ``` |
327 | /// | |
328 | /// At first, we have no memory allocated at all, but as we append to the | |
329 | /// string, it increases its capacity appropriately. If we instead use the | |
cc61c64b | 330 | /// [`with_capacity`] method to allocate the correct capacity initially: |
92a42be0 SL |
331 | /// |
332 | /// ``` | |
333 | /// let mut s = String::with_capacity(25); | |
334 | /// | |
335 | /// println!("{}", s.capacity()); | |
336 | /// | |
337 | /// for _ in 0..5 { | |
338 | /// s.push_str("hello"); | |
339 | /// println!("{}", s.capacity()); | |
340 | /// } | |
341 | /// ``` | |
342 | /// | |
3dfed10e | 343 | /// [`with_capacity`]: String::with_capacity |
92a42be0 SL |
344 | /// |
345 | /// We end up with a different output: | |
346 | /// | |
347 | /// ```text | |
348 | /// 25 | |
349 | /// 25 | |
350 | /// 25 | |
351 | /// 25 | |
352 | /// 25 | |
353 | /// 25 | |
354 | /// ``` | |
355 | /// | |
356 | /// Here, there's no need to allocate more memory inside the loop. | |
3b2f2976 | 357 | /// |
c295e0f8 XL |
358 | /// [str]: prim@str "str" |
359 | /// [`str`]: prim@str "str" | |
360 | /// [`&str`]: prim@str "&str" | |
361 | /// [Deref]: core::ops::Deref "ops::Deref" | |
362 | /// [`Deref`]: core::ops::Deref "ops::Deref" | |
3dfed10e | 363 | /// [`as_str()`]: String::as_str |
b039eaaf | 364 | #[derive(PartialOrd, Eq, Ord)] |
c295e0f8 | 365 | #[cfg_attr(not(test), rustc_diagnostic_item = "String")] |
85aaf69f | 366 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
367 | pub struct String { |
368 | vec: Vec<u8>, | |
369 | } | |
370 | ||
92a42be0 SL |
371 | /// A possible error value when converting a `String` from a UTF-8 byte vector. |
372 | /// | |
cc61c64b | 373 | /// This type is the error type for the [`from_utf8`] method on [`String`]. It |
92a42be0 | 374 | /// is designed in such a way to carefully avoid reallocations: the |
cc61c64b | 375 | /// [`into_bytes`] method will give back the byte vector that was used in the |
92a42be0 SL |
376 | /// conversion attempt. |
377 | /// | |
3dfed10e XL |
378 | /// [`from_utf8`]: String::from_utf8 |
379 | /// [`into_bytes`]: FromUtf8Error::into_bytes | |
92a42be0 SL |
380 | /// |
381 | /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may | |
382 | /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's | |
383 | /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error` | |
cc61c64b | 384 | /// through the [`utf8_error`] method. |
92a42be0 | 385 | /// |
c295e0f8 XL |
386 | /// [`Utf8Error`]: str::Utf8Error "std::str::Utf8Error" |
387 | /// [`std::str`]: core::str "std::str" | |
388 | /// [`&str`]: prim@str "&str" | |
389 | /// [`utf8_error`]: FromUtf8Error::utf8_error | |
92a42be0 SL |
390 | /// |
391 | /// # Examples | |
392 | /// | |
393 | /// Basic usage: | |
394 | /// | |
395 | /// ``` | |
396 | /// // some invalid bytes, in a vector | |
397 | /// let bytes = vec![0, 159]; | |
398 | /// | |
399 | /// let value = String::from_utf8(bytes); | |
400 | /// | |
401 | /// assert!(value.is_err()); | |
402 | /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes()); | |
403 | /// ``` | |
85aaf69f | 404 | #[stable(feature = "rust1", since = "1.0.0")] |
17df50a5 XL |
405 | #[cfg_attr(not(no_global_oom_handling), derive(Clone))] |
406 | #[derive(Debug, PartialEq, Eq)] | |
1a4d82fc JJ |
407 | pub struct FromUtf8Error { |
408 | bytes: Vec<u8>, | |
409 | error: Utf8Error, | |
410 | } | |
411 | ||
92a42be0 SL |
412 | /// A possible error value when converting a `String` from a UTF-16 byte slice. |
413 | /// | |
cc61c64b | 414 | /// This type is the error type for the [`from_utf16`] method on [`String`]. |
92a42be0 | 415 | /// |
3dfed10e | 416 | /// [`from_utf16`]: String::from_utf16 |
92a42be0 SL |
417 | /// # Examples |
418 | /// | |
419 | /// Basic usage: | |
420 | /// | |
421 | /// ``` | |
422 | /// // 𝄞mu<invalid>ic | |
423 | /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075, | |
424 | /// 0xD800, 0x0069, 0x0063]; | |
425 | /// | |
426 | /// assert!(String::from_utf16(v).is_err()); | |
427 | /// ``` | |
85aaf69f SL |
428 | #[stable(feature = "rust1", since = "1.0.0")] |
429 | #[derive(Debug)] | |
1a4d82fc JJ |
430 | pub struct FromUtf16Error(()); |
431 | ||
432 | impl String { | |
9cc50fc6 SL |
433 | /// Creates a new empty `String`. |
434 | /// | |
435 | /// Given that the `String` is empty, this will not allocate any initial | |
436 | /// buffer. While that means that this initial operation is very | |
0531ce1d | 437 | /// inexpensive, it may cause excessive allocation later when you add |
9cc50fc6 | 438 | /// data. If you have an idea of how much data the `String` will hold, |
cc61c64b | 439 | /// consider the [`with_capacity`] method to prevent excessive |
9cc50fc6 SL |
440 | /// re-allocation. |
441 | /// | |
3dfed10e | 442 | /// [`with_capacity`]: String::with_capacity |
1a4d82fc JJ |
443 | /// |
444 | /// # Examples | |
445 | /// | |
9cc50fc6 SL |
446 | /// Basic usage: |
447 | /// | |
1a4d82fc | 448 | /// ``` |
9cc50fc6 | 449 | /// let s = String::new(); |
1a4d82fc JJ |
450 | /// ``` |
451 | #[inline] | |
cdc7bbd5 | 452 | #[rustc_const_stable(feature = "const_string_new", since = "1.39.0")] |
85aaf69f | 453 | #[stable(feature = "rust1", since = "1.0.0")] |
c295e0f8 | 454 | #[must_use] |
94b46f34 | 455 | pub const fn new() -> String { |
92a42be0 | 456 | String { vec: Vec::new() } |
1a4d82fc JJ |
457 | } |
458 | ||
923072b8 | 459 | /// Creates a new empty `String` with at least the specified capacity. |
9cc50fc6 SL |
460 | /// |
461 | /// `String`s have an internal buffer to hold their data. The capacity is | |
cc61c64b | 462 | /// the length of that buffer, and can be queried with the [`capacity`] |
9cc50fc6 | 463 | /// method. This method creates an empty `String`, but one with an initial |
923072b8 FG |
464 | /// buffer that can hold at least `capacity` bytes. This is useful when you |
465 | /// may be appending a bunch of data to the `String`, reducing the number of | |
9cc50fc6 SL |
466 | /// reallocations it needs to do. |
467 | /// | |
3dfed10e | 468 | /// [`capacity`]: String::capacity |
9cc50fc6 SL |
469 | /// |
470 | /// If the given capacity is `0`, no allocation will occur, and this method | |
cc61c64b | 471 | /// is identical to the [`new`] method. |
9cc50fc6 | 472 | /// |
3dfed10e | 473 | /// [`new`]: String::new |
1a4d82fc JJ |
474 | /// |
475 | /// # Examples | |
476 | /// | |
9cc50fc6 SL |
477 | /// Basic usage: |
478 | /// | |
1a4d82fc JJ |
479 | /// ``` |
480 | /// let mut s = String::with_capacity(10); | |
92a42be0 SL |
481 | /// |
482 | /// // The String contains no chars, even though it has capacity for more | |
483 | /// assert_eq!(s.len(), 0); | |
484 | /// | |
485 | /// // These are all done without reallocating... | |
486 | /// let cap = s.capacity(); | |
a1dfa0c6 | 487 | /// for _ in 0..10 { |
92a42be0 SL |
488 | /// s.push('a'); |
489 | /// } | |
490 | /// | |
491 | /// assert_eq!(s.capacity(), cap); | |
492 | /// | |
74b04a01 | 493 | /// // ...but this may make the string reallocate |
92a42be0 | 494 | /// s.push('a'); |
1a4d82fc | 495 | /// ``` |
17df50a5 | 496 | #[cfg(not(no_global_oom_handling))] |
1a4d82fc | 497 | #[inline] |
85aaf69f | 498 | #[stable(feature = "rust1", since = "1.0.0")] |
c295e0f8 | 499 | #[must_use] |
85aaf69f | 500 | pub fn with_capacity(capacity: usize) -> String { |
92a42be0 | 501 | String { vec: Vec::with_capacity(capacity) } |
1a4d82fc JJ |
502 | } |
503 | ||
c34b1796 AL |
504 | // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is |
505 | // required for this method definition, is not available. Since we don't | |
506 | // require this method for testing purposes, I'll just stub it | |
507 | // NB see the slice::hack module in slice.rs for more information | |
508 | #[inline] | |
509 | #[cfg(test)] | |
510 | pub fn from_str(_: &str) -> String { | |
511 | panic!("not available with cfg(test)"); | |
1a4d82fc JJ |
512 | } |
513 | ||
b039eaaf SL |
514 | /// Converts a vector of bytes to a `String`. |
515 | /// | |
e74abb32 | 516 | /// A string ([`String`]) is made of bytes ([`u8`]), and a vector of bytes |
9cc50fc6 | 517 | /// ([`Vec<u8>`]) is made of bytes, so this function converts between the |
b039eaaf SL |
518 | /// two. Not all byte slices are valid `String`s, however: `String` |
519 | /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that | |
520 | /// the bytes are valid UTF-8, and then does the conversion. | |
521 | /// | |
522 | /// If you are sure that the byte slice is valid UTF-8, and you don't want | |
523 | /// to incur the overhead of the validity check, there is an unsafe version | |
cc61c64b | 524 | /// of this function, [`from_utf8_unchecked`], which has the same behavior |
9cc50fc6 | 525 | /// but skips the check. |
b039eaaf | 526 | /// |
b039eaaf SL |
527 | /// This method will take care to not copy the vector, for efficiency's |
528 | /// sake. | |
529 | /// | |
3b2f2976 | 530 | /// If you need a [`&str`] instead of a `String`, consider |
cc61c64b | 531 | /// [`str::from_utf8`]. |
b039eaaf | 532 | /// |
e74abb32 | 533 | /// The inverse of this method is [`into_bytes`]. |
8bb4bdeb | 534 | /// |
7453a54e | 535 | /// # Errors |
1a4d82fc | 536 | /// |
3b2f2976 | 537 | /// Returns [`Err`] if the slice is not UTF-8 with a description as to why the |
b039eaaf | 538 | /// provided bytes are not UTF-8. The vector you moved in is also included. |
1a4d82fc JJ |
539 | /// |
540 | /// # Examples | |
541 | /// | |
b039eaaf SL |
542 | /// Basic usage: |
543 | /// | |
c34b1796 | 544 | /// ``` |
b039eaaf SL |
545 | /// // some bytes, in a vector |
546 | /// let sparkle_heart = vec![240, 159, 146, 150]; | |
547 | /// | |
92a42be0 | 548 | /// // We know these bytes are valid, so we'll use `unwrap()`. |
b039eaaf SL |
549 | /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap(); |
550 | /// | |
551 | /// assert_eq!("💖", sparkle_heart); | |
552 | /// ``` | |
553 | /// | |
554 | /// Incorrect bytes: | |
555 | /// | |
1a4d82fc | 556 | /// ``` |
b039eaaf SL |
557 | /// // some invalid bytes, in a vector |
558 | /// let sparkle_heart = vec![0, 159, 146, 150]; | |
559 | /// | |
560 | /// assert!(String::from_utf8(sparkle_heart).is_err()); | |
561 | /// ``` | |
562 | /// | |
9cc50fc6 SL |
563 | /// See the docs for [`FromUtf8Error`] for more details on what you can do |
564 | /// with this error. | |
b039eaaf | 565 | /// |
3dfed10e | 566 | /// [`from_utf8_unchecked`]: String::from_utf8_unchecked |
c295e0f8 XL |
567 | /// [`Vec<u8>`]: crate::vec::Vec "Vec" |
568 | /// [`&str`]: prim@str "&str" | |
3dfed10e | 569 | /// [`into_bytes`]: String::into_bytes |
1a4d82fc | 570 | #[inline] |
85aaf69f | 571 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 572 | pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> { |
85aaf69f | 573 | match str::from_utf8(&vec) { |
a1dfa0c6 | 574 | Ok(..) => Ok(String { vec }), |
dfeec247 | 575 | Err(e) => Err(FromUtf8Error { bytes: vec, error: e }), |
1a4d82fc JJ |
576 | } |
577 | } | |
578 | ||
7453a54e | 579 | /// Converts a slice of bytes to a string, including invalid characters. |
b039eaaf | 580 | /// |
7453a54e SL |
581 | /// Strings are made of bytes ([`u8`]), and a slice of bytes |
582 | /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts | |
583 | /// between the two. Not all byte slices are valid strings, however: strings | |
584 | /// are required to be valid UTF-8. During this conversion, | |
9cc50fc6 | 585 | /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with |
b7449926 | 586 | /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD], which looks like this: � |
b039eaaf | 587 | /// |
6a06907d | 588 | /// [byteslice]: prim@slice |
3dfed10e | 589 | /// [U+FFFD]: core::char::REPLACEMENT_CHARACTER |
9cc50fc6 | 590 | /// |
b039eaaf SL |
591 | /// If you are sure that the byte slice is valid UTF-8, and you don't want |
592 | /// to incur the overhead of the conversion, there is an unsafe version | |
cc61c64b | 593 | /// of this function, [`from_utf8_unchecked`], which has the same behavior |
9cc50fc6 | 594 | /// but skips the checks. |
b039eaaf | 595 | /// |
3dfed10e | 596 | /// [`from_utf8_unchecked`]: String::from_utf8_unchecked |
b039eaaf | 597 | /// |
7453a54e SL |
598 | /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid |
599 | /// UTF-8, then we need to insert the replacement characters, which will | |
600 | /// change the size of the string, and hence, require a `String`. But if | |
601 | /// it's already valid UTF-8, we don't need a new allocation. This return | |
602 | /// type allows us to handle both cases. | |
b039eaaf | 603 | /// |
c295e0f8 | 604 | /// [`Cow<'a, str>`]: crate::borrow::Cow "borrow::Cow" |
1a4d82fc JJ |
605 | /// |
606 | /// # Examples | |
607 | /// | |
b039eaaf SL |
608 | /// Basic usage: |
609 | /// | |
c34b1796 | 610 | /// ``` |
b039eaaf SL |
611 | /// // some bytes, in a vector |
612 | /// let sparkle_heart = vec![240, 159, 146, 150]; | |
613 | /// | |
7453a54e | 614 | /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart); |
b039eaaf SL |
615 | /// |
616 | /// assert_eq!("💖", sparkle_heart); | |
617 | /// ``` | |
618 | /// | |
619 | /// Incorrect bytes: | |
620 | /// | |
621 | /// ``` | |
622 | /// // some invalid bytes | |
1a4d82fc JJ |
623 | /// let input = b"Hello \xF0\x90\x80World"; |
624 | /// let output = String::from_utf8_lossy(input); | |
b039eaaf SL |
625 | /// |
626 | /// assert_eq!("Hello �World", output); | |
1a4d82fc | 627 | /// ``` |
3c0e092e | 628 | #[must_use] |
17df50a5 | 629 | #[cfg(not(no_global_oom_handling))] |
85aaf69f | 630 | #[stable(feature = "rust1", since = "1.0.0")] |
416331ca | 631 | pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str> { |
f2b60f7d | 632 | let mut iter = Utf8Chunks::new(v); |
1a4d82fc | 633 | |
a2a8927a | 634 | let first_valid = if let Some(chunk) = iter.next() { |
f2b60f7d FG |
635 | let valid = chunk.valid(); |
636 | if chunk.invalid().is_empty() { | |
a2a8927a | 637 | debug_assert_eq!(valid.len(), v.len()); |
041b39d2 XL |
638 | return Cow::Borrowed(valid); |
639 | } | |
a2a8927a | 640 | valid |
041b39d2 XL |
641 | } else { |
642 | return Cow::Borrowed(""); | |
643 | }; | |
1a4d82fc | 644 | |
0731742a | 645 | const REPLACEMENT: &str = "\u{FFFD}"; |
1a4d82fc | 646 | |
041b39d2 XL |
647 | let mut res = String::with_capacity(v.len()); |
648 | res.push_str(first_valid); | |
a2a8927a | 649 | res.push_str(REPLACEMENT); |
1a4d82fc | 650 | |
f2b60f7d FG |
651 | for chunk in iter { |
652 | res.push_str(chunk.valid()); | |
653 | if !chunk.invalid().is_empty() { | |
041b39d2 | 654 | res.push_str(REPLACEMENT); |
1a4d82fc JJ |
655 | } |
656 | } | |
041b39d2 | 657 | |
1a4d82fc JJ |
658 | Cow::Owned(res) |
659 | } | |
660 | ||
29967ef6 | 661 | /// Decode a UTF-16–encoded vector `v` into a `String`, returning [`Err`] |
1a4d82fc JJ |
662 | /// if `v` contains any invalid data. |
663 | /// | |
664 | /// # Examples | |
665 | /// | |
9cc50fc6 SL |
666 | /// Basic usage: |
667 | /// | |
c34b1796 | 668 | /// ``` |
1a4d82fc | 669 | /// // 𝄞music |
92a42be0 SL |
670 | /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075, |
671 | /// 0x0073, 0x0069, 0x0063]; | |
9cc50fc6 SL |
672 | /// assert_eq!(String::from("𝄞music"), |
673 | /// String::from_utf16(v).unwrap()); | |
1a4d82fc JJ |
674 | /// |
675 | /// // 𝄞mu<invalid>ic | |
92a42be0 SL |
676 | /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075, |
677 | /// 0xD800, 0x0069, 0x0063]; | |
1a4d82fc JJ |
678 | /// assert!(String::from_utf16(v).is_err()); |
679 | /// ``` | |
17df50a5 | 680 | #[cfg(not(no_global_oom_handling))] |
85aaf69f | 681 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 682 | pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> { |
a1dfa0c6 XL |
683 | // This isn't done via collect::<Result<_, _>>() for performance reasons. |
684 | // FIXME: the function can be simplified again when #48994 is closed. | |
685 | let mut ret = String::with_capacity(v.len()); | |
686 | for c in decode_utf16(v.iter().cloned()) { | |
687 | if let Ok(c) = c { | |
688 | ret.push(c); | |
689 | } else { | |
690 | return Err(FromUtf16Error(())); | |
691 | } | |
692 | } | |
693 | Ok(ret) | |
1a4d82fc JJ |
694 | } |
695 | ||
29967ef6 | 696 | /// Decode a UTF-16–encoded slice `v` into a `String`, replacing |
b7449926 | 697 | /// invalid data with [the replacement character (`U+FFFD`)][U+FFFD]. |
1a4d82fc | 698 | /// |
ea8adc8c XL |
699 | /// Unlike [`from_utf8_lossy`] which returns a [`Cow<'a, str>`], |
700 | /// `from_utf16_lossy` returns a `String` since the UTF-16 to UTF-8 | |
701 | /// conversion requires a memory allocation. | |
702 | /// | |
3dfed10e | 703 | /// [`from_utf8_lossy`]: String::from_utf8_lossy |
c295e0f8 | 704 | /// [`Cow<'a, str>`]: crate::borrow::Cow "borrow::Cow" |
3dfed10e | 705 | /// [U+FFFD]: core::char::REPLACEMENT_CHARACTER |
ea8adc8c | 706 | /// |
1a4d82fc JJ |
707 | /// # Examples |
708 | /// | |
9cc50fc6 SL |
709 | /// Basic usage: |
710 | /// | |
c34b1796 | 711 | /// ``` |
1a4d82fc JJ |
712 | /// // 𝄞mus<invalid>ic<invalid> |
713 | /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075, | |
714 | /// 0x0073, 0xDD1E, 0x0069, 0x0063, | |
715 | /// 0xD834]; | |
716 | /// | |
9cc50fc6 SL |
717 | /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"), |
718 | /// String::from_utf16_lossy(v)); | |
1a4d82fc | 719 | /// ``` |
17df50a5 | 720 | #[cfg(not(no_global_oom_handling))] |
3c0e092e | 721 | #[must_use] |
85aaf69f SL |
722 | #[inline] |
723 | #[stable(feature = "rust1", since = "1.0.0")] | |
1a4d82fc | 724 | pub fn from_utf16_lossy(v: &[u16]) -> String { |
e9174d1e | 725 | decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect() |
1a4d82fc JJ |
726 | } |
727 | ||
e74abb32 XL |
728 | /// Decomposes a `String` into its raw components. |
729 | /// | |
730 | /// Returns the raw pointer to the underlying data, the length of | |
731 | /// the string (in bytes), and the allocated capacity of the data | |
732 | /// (in bytes). These are the same arguments in the same order as | |
733 | /// the arguments to [`from_raw_parts`]. | |
734 | /// | |
735 | /// After calling this function, the caller is responsible for the | |
736 | /// memory previously managed by the `String`. The only way to do | |
737 | /// this is to convert the raw pointer, length, and capacity back | |
738 | /// into a `String` with the [`from_raw_parts`] function, allowing | |
739 | /// the destructor to perform the cleanup. | |
740 | /// | |
3dfed10e | 741 | /// [`from_raw_parts`]: String::from_raw_parts |
e74abb32 XL |
742 | /// |
743 | /// # Examples | |
744 | /// | |
745 | /// ``` | |
746 | /// #![feature(vec_into_raw_parts)] | |
747 | /// let s = String::from("hello"); | |
748 | /// | |
749 | /// let (ptr, len, cap) = s.into_raw_parts(); | |
750 | /// | |
751 | /// let rebuilt = unsafe { String::from_raw_parts(ptr, len, cap) }; | |
752 | /// assert_eq!(rebuilt, "hello"); | |
753 | /// ``` | |
c295e0f8 | 754 | #[must_use = "`self` will be dropped if the result is not used"] |
e74abb32 XL |
755 | #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")] |
756 | pub fn into_raw_parts(self) -> (*mut u8, usize, usize) { | |
757 | self.vec.into_raw_parts() | |
758 | } | |
759 | ||
1a4d82fc JJ |
760 | /// Creates a new `String` from a length, capacity, and pointer. |
761 | /// | |
b039eaaf | 762 | /// # Safety |
c1a9b12d | 763 | /// |
9cc50fc6 SL |
764 | /// This is highly unsafe, due to the number of invariants that aren't |
765 | /// checked: | |
766 | /// | |
3dfed10e | 767 | /// * The memory at `buf` needs to have been previously allocated by the |
60c5eb7d | 768 | /// same allocator the standard library uses, with a required alignment of exactly 1. |
9cc50fc6 SL |
769 | /// * `length` needs to be less than or equal to `capacity`. |
770 | /// * `capacity` needs to be the correct value. | |
3dfed10e | 771 | /// * The first `length` bytes at `buf` need to be valid UTF-8. |
9cc50fc6 SL |
772 | /// |
773 | /// Violating these may cause problems like corrupting the allocator's | |
04454e1e FG |
774 | /// internal data structures. For example, it is normally **not** safe to |
775 | /// build a `String` from a pointer to a C `char` array containing UTF-8 | |
776 | /// _unless_ you are certain that array was originally allocated by the | |
777 | /// Rust standard library's allocator. | |
9cc50fc6 | 778 | /// |
3dfed10e | 779 | /// The ownership of `buf` is effectively transferred to the |
5bcae85e SL |
780 | /// `String` which may then deallocate, reallocate or change the |
781 | /// contents of memory pointed to by the pointer at will. Ensure | |
782 | /// that nothing else uses the pointer after calling this | |
783 | /// function. | |
784 | /// | |
9cc50fc6 SL |
785 | /// # Examples |
786 | /// | |
787 | /// Basic usage: | |
788 | /// | |
789 | /// ``` | |
790 | /// use std::mem; | |
791 | /// | |
792 | /// unsafe { | |
793 | /// let s = String::from("hello"); | |
e74abb32 XL |
794 | /// |
795 | // FIXME Update this when vec_into_raw_parts is stabilized | |
796 | /// // Prevent automatically dropping the String's data | |
797 | /// let mut s = mem::ManuallyDrop::new(s); | |
798 | /// | |
799 | /// let ptr = s.as_mut_ptr(); | |
9cc50fc6 SL |
800 | /// let len = s.len(); |
801 | /// let capacity = s.capacity(); | |
802 | /// | |
e74abb32 | 803 | /// let s = String::from_raw_parts(ptr, len, capacity); |
c34b1796 | 804 | /// |
9cc50fc6 SL |
805 | /// assert_eq!(String::from("hello"), s); |
806 | /// } | |
807 | /// ``` | |
1a4d82fc | 808 | #[inline] |
85aaf69f SL |
809 | #[stable(feature = "rust1", since = "1.0.0")] |
810 | pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String { | |
f035d41b | 811 | unsafe { String { vec: Vec::from_raw_parts(buf, length, capacity) } } |
1a4d82fc JJ |
812 | } |
813 | ||
b039eaaf SL |
814 | /// Converts a vector of bytes to a `String` without checking that the |
815 | /// string contains valid UTF-8. | |
816 | /// | |
cc61c64b | 817 | /// See the safe version, [`from_utf8`], for more details. |
b039eaaf | 818 | /// |
3dfed10e | 819 | /// [`from_utf8`]: String::from_utf8 |
b039eaaf SL |
820 | /// |
821 | /// # Safety | |
822 | /// | |
9cc50fc6 SL |
823 | /// This function is unsafe because it does not check that the bytes passed |
824 | /// to it are valid UTF-8. If this constraint is violated, it may cause | |
825 | /// memory unsafety issues with future users of the `String`, as the rest of | |
826 | /// the standard library assumes that `String`s are valid UTF-8. | |
b039eaaf SL |
827 | /// |
828 | /// # Examples | |
829 | /// | |
830 | /// Basic usage: | |
831 | /// | |
832 | /// ``` | |
833 | /// // some bytes, in a vector | |
834 | /// let sparkle_heart = vec![240, 159, 146, 150]; | |
835 | /// | |
836 | /// let sparkle_heart = unsafe { | |
837 | /// String::from_utf8_unchecked(sparkle_heart) | |
838 | /// }; | |
839 | /// | |
840 | /// assert_eq!("💖", sparkle_heart); | |
841 | /// ``` | |
1a4d82fc | 842 | #[inline] |
c295e0f8 | 843 | #[must_use] |
85aaf69f | 844 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
845 | pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String { |
846 | String { vec: bytes } | |
847 | } | |
848 | ||
9cc50fc6 SL |
849 | /// Converts a `String` into a byte vector. |
850 | /// | |
851 | /// This consumes the `String`, so we do not need to copy its contents. | |
1a4d82fc JJ |
852 | /// |
853 | /// # Examples | |
854 | /// | |
9cc50fc6 SL |
855 | /// Basic usage: |
856 | /// | |
1a4d82fc | 857 | /// ``` |
62682a34 | 858 | /// let s = String::from("hello"); |
1a4d82fc | 859 | /// let bytes = s.into_bytes(); |
9cc50fc6 SL |
860 | /// |
861 | /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]); | |
1a4d82fc JJ |
862 | /// ``` |
863 | #[inline] | |
c295e0f8 | 864 | #[must_use = "`self` will be dropped if the result is not used"] |
85aaf69f | 865 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
866 | pub fn into_bytes(self) -> Vec<u8> { |
867 | self.vec | |
868 | } | |
869 | ||
b7449926 | 870 | /// Extracts a string slice containing the entire `String`. |
ea8adc8c XL |
871 | /// |
872 | /// # Examples | |
873 | /// | |
874 | /// Basic usage: | |
875 | /// | |
876 | /// ``` | |
877 | /// let s = String::from("foo"); | |
878 | /// | |
879 | /// assert_eq!("foo", s.as_str()); | |
880 | /// ``` | |
c34b1796 | 881 | #[inline] |
c295e0f8 | 882 | #[must_use] |
9cc50fc6 | 883 | #[stable(feature = "string_as_str", since = "1.7.0")] |
c34b1796 AL |
884 | pub fn as_str(&self) -> &str { |
885 | self | |
886 | } | |
887 | ||
ea8adc8c XL |
888 | /// Converts a `String` into a mutable string slice. |
889 | /// | |
890 | /// # Examples | |
891 | /// | |
892 | /// Basic usage: | |
893 | /// | |
894 | /// ``` | |
ea8adc8c XL |
895 | /// let mut s = String::from("foobar"); |
896 | /// let s_mut_str = s.as_mut_str(); | |
897 | /// | |
898 | /// s_mut_str.make_ascii_uppercase(); | |
899 | /// | |
900 | /// assert_eq!("FOOBAR", s_mut_str); | |
901 | /// ``` | |
9cc50fc6 | 902 | #[inline] |
c295e0f8 | 903 | #[must_use] |
9cc50fc6 SL |
904 | #[stable(feature = "string_as_str", since = "1.7.0")] |
905 | pub fn as_mut_str(&mut self) -> &mut str { | |
906 | self | |
907 | } | |
908 | ||
909 | /// Appends a given string slice onto the end of this `String`. | |
1a4d82fc JJ |
910 | /// |
911 | /// # Examples | |
912 | /// | |
9cc50fc6 SL |
913 | /// Basic usage: |
914 | /// | |
1a4d82fc | 915 | /// ``` |
62682a34 | 916 | /// let mut s = String::from("foo"); |
9cc50fc6 | 917 | /// |
1a4d82fc | 918 | /// s.push_str("bar"); |
9cc50fc6 SL |
919 | /// |
920 | /// assert_eq!("foobar", s); | |
1a4d82fc | 921 | /// ``` |
17df50a5 | 922 | #[cfg(not(no_global_oom_handling))] |
1a4d82fc | 923 | #[inline] |
85aaf69f | 924 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 925 | pub fn push_str(&mut self, string: &str) { |
92a42be0 | 926 | self.vec.extend_from_slice(string.as_bytes()) |
1a4d82fc JJ |
927 | } |
928 | ||
17df50a5 XL |
929 | /// Copies elements from `src` range to the end of the string. |
930 | /// | |
931 | /// ## Panics | |
932 | /// | |
933 | /// Panics if the starting point or end point do not lie on a [`char`] | |
934 | /// boundary, or if they're out of bounds. | |
935 | /// | |
936 | /// ## Examples | |
937 | /// | |
938 | /// ``` | |
939 | /// #![feature(string_extend_from_within)] | |
940 | /// let mut string = String::from("abcde"); | |
941 | /// | |
942 | /// string.extend_from_within(2..); | |
943 | /// assert_eq!(string, "abcdecde"); | |
944 | /// | |
945 | /// string.extend_from_within(..2); | |
946 | /// assert_eq!(string, "abcdecdeab"); | |
947 | /// | |
948 | /// string.extend_from_within(4..8); | |
949 | /// assert_eq!(string, "abcdecdeabecde"); | |
950 | /// ``` | |
951 | #[cfg(not(no_global_oom_handling))] | |
952 | #[unstable(feature = "string_extend_from_within", issue = "none")] | |
953 | pub fn extend_from_within<R>(&mut self, src: R) | |
954 | where | |
955 | R: RangeBounds<usize>, | |
956 | { | |
957 | let src @ Range { start, end } = slice::range(src, ..self.len()); | |
958 | ||
959 | assert!(self.is_char_boundary(start)); | |
960 | assert!(self.is_char_boundary(end)); | |
961 | ||
962 | self.vec.extend_from_within(src); | |
963 | } | |
964 | ||
9cc50fc6 | 965 | /// Returns this `String`'s capacity, in bytes. |
1a4d82fc JJ |
966 | /// |
967 | /// # Examples | |
968 | /// | |
9cc50fc6 SL |
969 | /// Basic usage: |
970 | /// | |
1a4d82fc JJ |
971 | /// ``` |
972 | /// let s = String::with_capacity(10); | |
9cc50fc6 | 973 | /// |
1a4d82fc JJ |
974 | /// assert!(s.capacity() >= 10); |
975 | /// ``` | |
976 | #[inline] | |
3c0e092e | 977 | #[must_use] |
85aaf69f SL |
978 | #[stable(feature = "rust1", since = "1.0.0")] |
979 | pub fn capacity(&self) -> usize { | |
1a4d82fc JJ |
980 | self.vec.capacity() |
981 | } | |
982 | ||
923072b8 FG |
983 | /// Reserves capacity for at least `additional` bytes more than the |
984 | /// current length. The allocator may reserve more space to speculatively | |
985 | /// avoid frequent allocations. After calling `reserve`, | |
986 | /// capacity will be greater than or equal to `self.len() + additional`. | |
987 | /// Does nothing if capacity is already sufficient. | |
9cc50fc6 | 988 | /// |
1a4d82fc JJ |
989 | /// # Panics |
990 | /// | |
3b2f2976 XL |
991 | /// Panics if the new capacity overflows [`usize`]. |
992 | /// | |
1a4d82fc JJ |
993 | /// # Examples |
994 | /// | |
9cc50fc6 SL |
995 | /// Basic usage: |
996 | /// | |
1a4d82fc JJ |
997 | /// ``` |
998 | /// let mut s = String::new(); | |
9cc50fc6 | 999 | /// |
1a4d82fc | 1000 | /// s.reserve(10); |
9cc50fc6 | 1001 | /// |
1a4d82fc JJ |
1002 | /// assert!(s.capacity() >= 10); |
1003 | /// ``` | |
9cc50fc6 | 1004 | /// |
94222f64 | 1005 | /// This might not actually increase the capacity: |
9cc50fc6 SL |
1006 | /// |
1007 | /// ``` | |
1008 | /// let mut s = String::with_capacity(10); | |
1009 | /// s.push('a'); | |
1010 | /// s.push('b'); | |
1011 | /// | |
923072b8 FG |
1012 | /// // s now has a length of 2 and a capacity of at least 10 |
1013 | /// let capacity = s.capacity(); | |
9cc50fc6 | 1014 | /// assert_eq!(2, s.len()); |
923072b8 | 1015 | /// assert!(capacity >= 10); |
9cc50fc6 | 1016 | /// |
923072b8 | 1017 | /// // Since we already have at least an extra 8 capacity, calling this... |
9cc50fc6 SL |
1018 | /// s.reserve(8); |
1019 | /// | |
1020 | /// // ... doesn't actually increase. | |
923072b8 | 1021 | /// assert_eq!(capacity, s.capacity()); |
9cc50fc6 | 1022 | /// ``` |
17df50a5 | 1023 | #[cfg(not(no_global_oom_handling))] |
1a4d82fc | 1024 | #[inline] |
85aaf69f SL |
1025 | #[stable(feature = "rust1", since = "1.0.0")] |
1026 | pub fn reserve(&mut self, additional: usize) { | |
1a4d82fc JJ |
1027 | self.vec.reserve(additional) |
1028 | } | |
1029 | ||
923072b8 FG |
1030 | /// Reserves the minimum capacity for at least `additional` bytes more than |
1031 | /// the current length. Unlike [`reserve`], this will not | |
1032 | /// deliberately over-allocate to speculatively avoid frequent allocations. | |
1033 | /// After calling `reserve_exact`, capacity will be greater than or equal to | |
1034 | /// `self.len() + additional`. Does nothing if the capacity is already | |
1035 | /// sufficient. | |
9cc50fc6 | 1036 | /// |
3dfed10e | 1037 | /// [`reserve`]: String::reserve |
1a4d82fc JJ |
1038 | /// |
1039 | /// # Panics | |
1040 | /// | |
923072b8 | 1041 | /// Panics if the new capacity overflows [`usize`]. |
1a4d82fc JJ |
1042 | /// |
1043 | /// # Examples | |
1044 | /// | |
9cc50fc6 SL |
1045 | /// Basic usage: |
1046 | /// | |
1a4d82fc JJ |
1047 | /// ``` |
1048 | /// let mut s = String::new(); | |
9cc50fc6 | 1049 | /// |
62682a34 | 1050 | /// s.reserve_exact(10); |
9cc50fc6 | 1051 | /// |
1a4d82fc JJ |
1052 | /// assert!(s.capacity() >= 10); |
1053 | /// ``` | |
9cc50fc6 | 1054 | /// |
94222f64 | 1055 | /// This might not actually increase the capacity: |
9cc50fc6 SL |
1056 | /// |
1057 | /// ``` | |
1058 | /// let mut s = String::with_capacity(10); | |
1059 | /// s.push('a'); | |
1060 | /// s.push('b'); | |
1061 | /// | |
923072b8 FG |
1062 | /// // s now has a length of 2 and a capacity of at least 10 |
1063 | /// let capacity = s.capacity(); | |
9cc50fc6 | 1064 | /// assert_eq!(2, s.len()); |
923072b8 | 1065 | /// assert!(capacity >= 10); |
9cc50fc6 | 1066 | /// |
923072b8 | 1067 | /// // Since we already have at least an extra 8 capacity, calling this... |
9cc50fc6 SL |
1068 | /// s.reserve_exact(8); |
1069 | /// | |
1070 | /// // ... doesn't actually increase. | |
923072b8 | 1071 | /// assert_eq!(capacity, s.capacity()); |
9cc50fc6 | 1072 | /// ``` |
17df50a5 | 1073 | #[cfg(not(no_global_oom_handling))] |
1a4d82fc | 1074 | #[inline] |
85aaf69f SL |
1075 | #[stable(feature = "rust1", since = "1.0.0")] |
1076 | pub fn reserve_exact(&mut self, additional: usize) { | |
1a4d82fc JJ |
1077 | self.vec.reserve_exact(additional) |
1078 | } | |
1079 | ||
923072b8 FG |
1080 | /// Tries to reserve capacity for at least `additional` bytes more than the |
1081 | /// current length. The allocator may reserve more space to speculatively | |
1082 | /// avoid frequent allocations. After calling `try_reserve`, capacity will be | |
1083 | /// greater than or equal to `self.len() + additional` if it returns | |
f2b60f7d FG |
1084 | /// `Ok(())`. Does nothing if capacity is already sufficient. This method |
1085 | /// preserves the contents even if an error occurs. | |
0531ce1d XL |
1086 | /// |
1087 | /// # Errors | |
1088 | /// | |
1089 | /// If the capacity overflows, or the allocator reports a failure, then an error | |
1090 | /// is returned. | |
1091 | /// | |
1092 | /// # Examples | |
1093 | /// | |
1094 | /// ``` | |
e1599b0c | 1095 | /// use std::collections::TryReserveError; |
0531ce1d | 1096 | /// |
e1599b0c | 1097 | /// fn process_data(data: &str) -> Result<String, TryReserveError> { |
0531ce1d XL |
1098 | /// let mut output = String::new(); |
1099 | /// | |
1100 | /// // Pre-reserve the memory, exiting if we can't | |
1101 | /// output.try_reserve(data.len())?; | |
1102 | /// | |
1103 | /// // Now we know this can't OOM in the middle of our complex work | |
1104 | /// output.push_str(data); | |
1105 | /// | |
1106 | /// Ok(output) | |
1107 | /// } | |
1108 | /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?"); | |
1109 | /// ``` | |
c295e0f8 | 1110 | #[stable(feature = "try_reserve", since = "1.57.0")] |
e1599b0c | 1111 | pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> { |
0531ce1d XL |
1112 | self.vec.try_reserve(additional) |
1113 | } | |
1114 | ||
923072b8 FG |
1115 | /// Tries to reserve the minimum capacity for at least `additional` bytes |
1116 | /// more than the current length. Unlike [`try_reserve`], this will not | |
1117 | /// deliberately over-allocate to speculatively avoid frequent allocations. | |
1118 | /// After calling `try_reserve_exact`, capacity will be greater than or | |
1119 | /// equal to `self.len() + additional` if it returns `Ok(())`. | |
0531ce1d XL |
1120 | /// Does nothing if the capacity is already sufficient. |
1121 | /// | |
1122 | /// Note that the allocator may give the collection more space than it | |
9fa01778 | 1123 | /// requests. Therefore, capacity can not be relied upon to be precisely |
a2a8927a | 1124 | /// minimal. Prefer [`try_reserve`] if future insertions are expected. |
94222f64 | 1125 | /// |
a2a8927a | 1126 | /// [`try_reserve`]: String::try_reserve |
0531ce1d XL |
1127 | /// |
1128 | /// # Errors | |
1129 | /// | |
1130 | /// If the capacity overflows, or the allocator reports a failure, then an error | |
1131 | /// is returned. | |
1132 | /// | |
1133 | /// # Examples | |
1134 | /// | |
1135 | /// ``` | |
e1599b0c | 1136 | /// use std::collections::TryReserveError; |
0531ce1d | 1137 | /// |
e1599b0c | 1138 | /// fn process_data(data: &str) -> Result<String, TryReserveError> { |
0531ce1d XL |
1139 | /// let mut output = String::new(); |
1140 | /// | |
1141 | /// // Pre-reserve the memory, exiting if we can't | |
a2a8927a | 1142 | /// output.try_reserve_exact(data.len())?; |
0531ce1d XL |
1143 | /// |
1144 | /// // Now we know this can't OOM in the middle of our complex work | |
1145 | /// output.push_str(data); | |
1146 | /// | |
1147 | /// Ok(output) | |
1148 | /// } | |
1149 | /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?"); | |
1150 | /// ``` | |
c295e0f8 | 1151 | #[stable(feature = "try_reserve", since = "1.57.0")] |
dfeec247 | 1152 | pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> { |
0531ce1d XL |
1153 | self.vec.try_reserve_exact(additional) |
1154 | } | |
1155 | ||
9cc50fc6 | 1156 | /// Shrinks the capacity of this `String` to match its length. |
1a4d82fc JJ |
1157 | /// |
1158 | /// # Examples | |
1159 | /// | |
9cc50fc6 SL |
1160 | /// Basic usage: |
1161 | /// | |
1a4d82fc | 1162 | /// ``` |
62682a34 | 1163 | /// let mut s = String::from("foo"); |
9cc50fc6 | 1164 | /// |
1a4d82fc JJ |
1165 | /// s.reserve(100); |
1166 | /// assert!(s.capacity() >= 100); | |
9cc50fc6 | 1167 | /// |
1a4d82fc | 1168 | /// s.shrink_to_fit(); |
9cc50fc6 | 1169 | /// assert_eq!(3, s.capacity()); |
1a4d82fc | 1170 | /// ``` |
17df50a5 | 1171 | #[cfg(not(no_global_oom_handling))] |
1a4d82fc | 1172 | #[inline] |
85aaf69f | 1173 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1174 | pub fn shrink_to_fit(&mut self) { |
1175 | self.vec.shrink_to_fit() | |
1176 | } | |
1177 | ||
0531ce1d XL |
1178 | /// Shrinks the capacity of this `String` with a lower bound. |
1179 | /// | |
1180 | /// The capacity will remain at least as large as both the length | |
1181 | /// and the supplied value. | |
1182 | /// | |
5869c6ff | 1183 | /// If the current capacity is less than the lower limit, this is a no-op. |
0531ce1d XL |
1184 | /// |
1185 | /// # Examples | |
1186 | /// | |
1187 | /// ``` | |
0531ce1d XL |
1188 | /// let mut s = String::from("foo"); |
1189 | /// | |
1190 | /// s.reserve(100); | |
1191 | /// assert!(s.capacity() >= 100); | |
1192 | /// | |
1193 | /// s.shrink_to(10); | |
1194 | /// assert!(s.capacity() >= 10); | |
1195 | /// s.shrink_to(0); | |
1196 | /// assert!(s.capacity() >= 3); | |
1197 | /// ``` | |
17df50a5 | 1198 | #[cfg(not(no_global_oom_handling))] |
0531ce1d | 1199 | #[inline] |
94222f64 | 1200 | #[stable(feature = "shrink_to", since = "1.56.0")] |
0531ce1d XL |
1201 | pub fn shrink_to(&mut self, min_capacity: usize) { |
1202 | self.vec.shrink_to(min_capacity) | |
1203 | } | |
1204 | ||
3b2f2976 XL |
1205 | /// Appends the given [`char`] to the end of this `String`. |
1206 | /// | |
1a4d82fc JJ |
1207 | /// # Examples |
1208 | /// | |
9cc50fc6 SL |
1209 | /// Basic usage: |
1210 | /// | |
1a4d82fc | 1211 | /// ``` |
62682a34 | 1212 | /// let mut s = String::from("abc"); |
9cc50fc6 | 1213 | /// |
1a4d82fc JJ |
1214 | /// s.push('1'); |
1215 | /// s.push('2'); | |
1216 | /// s.push('3'); | |
9cc50fc6 SL |
1217 | /// |
1218 | /// assert_eq!("abc123", s); | |
1a4d82fc | 1219 | /// ``` |
17df50a5 | 1220 | #[cfg(not(no_global_oom_handling))] |
1a4d82fc | 1221 | #[inline] |
85aaf69f | 1222 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 1223 | pub fn push(&mut self, ch: char) { |
62682a34 SL |
1224 | match ch.len_utf8() { |
1225 | 1 => self.vec.push(ch as u8), | |
32a655c1 | 1226 | _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()), |
1a4d82fc JJ |
1227 | } |
1228 | } | |
1229 | ||
9cc50fc6 | 1230 | /// Returns a byte slice of this `String`'s contents. |
1a4d82fc | 1231 | /// |
8bb4bdeb XL |
1232 | /// The inverse of this method is [`from_utf8`]. |
1233 | /// | |
3dfed10e | 1234 | /// [`from_utf8`]: String::from_utf8 |
8bb4bdeb | 1235 | /// |
1a4d82fc JJ |
1236 | /// # Examples |
1237 | /// | |
9cc50fc6 SL |
1238 | /// Basic usage: |
1239 | /// | |
1a4d82fc | 1240 | /// ``` |
62682a34 | 1241 | /// let s = String::from("hello"); |
9cc50fc6 SL |
1242 | /// |
1243 | /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes()); | |
1a4d82fc JJ |
1244 | /// ``` |
1245 | #[inline] | |
c295e0f8 | 1246 | #[must_use] |
85aaf69f SL |
1247 | #[stable(feature = "rust1", since = "1.0.0")] |
1248 | pub fn as_bytes(&self) -> &[u8] { | |
1249 | &self.vec | |
1a4d82fc JJ |
1250 | } |
1251 | ||
9cc50fc6 | 1252 | /// Shortens this `String` to the specified length. |
1a4d82fc | 1253 | /// |
a7813a04 XL |
1254 | /// If `new_len` is greater than the string's current length, this has no |
1255 | /// effect. | |
1256 | /// | |
8bb4bdeb XL |
1257 | /// Note that this method has no effect on the allocated capacity |
1258 | /// of the string | |
1259 | /// | |
1a4d82fc JJ |
1260 | /// # Panics |
1261 | /// | |
a7813a04 | 1262 | /// Panics if `new_len` does not lie on a [`char`] boundary. |
9cc50fc6 | 1263 | /// |
1a4d82fc JJ |
1264 | /// # Examples |
1265 | /// | |
9cc50fc6 SL |
1266 | /// Basic usage: |
1267 | /// | |
1a4d82fc | 1268 | /// ``` |
62682a34 | 1269 | /// let mut s = String::from("hello"); |
9cc50fc6 | 1270 | /// |
1a4d82fc | 1271 | /// s.truncate(2); |
9cc50fc6 SL |
1272 | /// |
1273 | /// assert_eq!("he", s); | |
1a4d82fc JJ |
1274 | /// ``` |
1275 | #[inline] | |
85aaf69f SL |
1276 | #[stable(feature = "rust1", since = "1.0.0")] |
1277 | pub fn truncate(&mut self, new_len: usize) { | |
a7813a04 XL |
1278 | if new_len <= self.len() { |
1279 | assert!(self.is_char_boundary(new_len)); | |
1280 | self.vec.truncate(new_len) | |
1281 | } | |
1a4d82fc JJ |
1282 | } |
1283 | ||
1284 | /// Removes the last character from the string buffer and returns it. | |
9cc50fc6 | 1285 | /// |
3b2f2976 XL |
1286 | /// Returns [`None`] if this `String` is empty. |
1287 | /// | |
1a4d82fc JJ |
1288 | /// # Examples |
1289 | /// | |
9cc50fc6 SL |
1290 | /// Basic usage: |
1291 | /// | |
1a4d82fc | 1292 | /// ``` |
62682a34 | 1293 | /// let mut s = String::from("foo"); |
9cc50fc6 | 1294 | /// |
1a4d82fc JJ |
1295 | /// assert_eq!(s.pop(), Some('o')); |
1296 | /// assert_eq!(s.pop(), Some('o')); | |
1297 | /// assert_eq!(s.pop(), Some('f')); | |
9cc50fc6 | 1298 | /// |
1a4d82fc JJ |
1299 | /// assert_eq!(s.pop(), None); |
1300 | /// ``` | |
1301 | #[inline] | |
85aaf69f | 1302 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 1303 | pub fn pop(&mut self) -> Option<char> { |
ff7c6d11 | 1304 | let ch = self.chars().rev().next()?; |
54a0048b | 1305 | let newlen = self.len() - ch.len_utf8(); |
1a4d82fc | 1306 | unsafe { |
54a0048b | 1307 | self.vec.set_len(newlen); |
1a4d82fc JJ |
1308 | } |
1309 | Some(ch) | |
1310 | } | |
1311 | ||
3b2f2976 | 1312 | /// Removes a [`char`] from this `String` at a byte position and returns it. |
1a4d82fc | 1313 | /// |
3dfed10e | 1314 | /// This is an *O*(*n*) operation, as it requires copying every element in the |
1a4d82fc JJ |
1315 | /// buffer. |
1316 | /// | |
1317 | /// # Panics | |
1318 | /// | |
9cc50fc6 SL |
1319 | /// Panics if `idx` is larger than or equal to the `String`'s length, |
1320 | /// or if it does not lie on a [`char`] boundary. | |
1321 | /// | |
1a4d82fc JJ |
1322 | /// # Examples |
1323 | /// | |
9cc50fc6 SL |
1324 | /// Basic usage: |
1325 | /// | |
1a4d82fc | 1326 | /// ``` |
62682a34 | 1327 | /// let mut s = String::from("foo"); |
9cc50fc6 | 1328 | /// |
1a4d82fc JJ |
1329 | /// assert_eq!(s.remove(0), 'f'); |
1330 | /// assert_eq!(s.remove(1), 'o'); | |
1331 | /// assert_eq!(s.remove(0), 'o'); | |
1332 | /// ``` | |
85aaf69f SL |
1333 | #[inline] |
1334 | #[stable(feature = "rust1", since = "1.0.0")] | |
1335 | pub fn remove(&mut self, idx: usize) -> char { | |
54a0048b SL |
1336 | let ch = match self[idx..].chars().next() { |
1337 | Some(ch) => ch, | |
1338 | None => panic!("cannot remove a char from the end of a string"), | |
1339 | }; | |
1a4d82fc | 1340 | |
c34b1796 | 1341 | let next = idx + ch.len_utf8(); |
54a0048b | 1342 | let len = self.len(); |
1a4d82fc | 1343 | unsafe { |
dfeec247 | 1344 | ptr::copy(self.vec.as_ptr().add(next), self.vec.as_mut_ptr().add(idx), len - next); |
1a4d82fc JJ |
1345 | self.vec.set_len(len - (next - idx)); |
1346 | } | |
1347 | ch | |
1348 | } | |
1349 | ||
6a06907d XL |
1350 | /// Remove all matches of pattern `pat` in the `String`. |
1351 | /// | |
1352 | /// # Examples | |
1353 | /// | |
1354 | /// ``` | |
1355 | /// #![feature(string_remove_matches)] | |
1356 | /// let mut s = String::from("Trees are not green, the sky is not blue."); | |
1357 | /// s.remove_matches("not "); | |
1358 | /// assert_eq!("Trees are green, the sky is blue.", s); | |
1359 | /// ``` | |
1360 | /// | |
1361 | /// Matches will be detected and removed iteratively, so in cases where | |
1362 | /// patterns overlap, only the first pattern will be removed: | |
1363 | /// | |
1364 | /// ``` | |
1365 | /// #![feature(string_remove_matches)] | |
1366 | /// let mut s = String::from("banana"); | |
1367 | /// s.remove_matches("ana"); | |
1368 | /// assert_eq!("bna", s); | |
1369 | /// ``` | |
17df50a5 | 1370 | #[cfg(not(no_global_oom_handling))] |
6a06907d XL |
1371 | #[unstable(feature = "string_remove_matches", reason = "new API", issue = "72826")] |
1372 | pub fn remove_matches<'a, P>(&'a mut self, pat: P) | |
1373 | where | |
1374 | P: for<'x> Pattern<'x>, | |
1375 | { | |
1376 | use core::str::pattern::Searcher; | |
1377 | ||
17df50a5 | 1378 | let rejections = { |
6a06907d | 1379 | let mut searcher = pat.into_searcher(self); |
17df50a5 XL |
1380 | // Per Searcher::next: |
1381 | // | |
1382 | // A Match result needs to contain the whole matched pattern, | |
1383 | // however Reject results may be split up into arbitrary many | |
1384 | // adjacent fragments. Both ranges may have zero length. | |
1385 | // | |
1386 | // In practice the implementation of Searcher::next_match tends to | |
1387 | // be more efficient, so we use it here and do some work to invert | |
1388 | // matches into rejections since that's what we want to copy below. | |
1389 | let mut front = 0; | |
1390 | let rejections: Vec<_> = from_fn(|| { | |
1391 | let (start, end) = searcher.next_match()?; | |
1392 | let prev_front = front; | |
1393 | front = end; | |
1394 | Some((prev_front, start)) | |
1395 | }) | |
1396 | .collect(); | |
1397 | rejections.into_iter().chain(core::iter::once((front, self.len()))) | |
6a06907d XL |
1398 | }; |
1399 | ||
17df50a5 XL |
1400 | let mut len = 0; |
1401 | let ptr = self.vec.as_mut_ptr(); | |
1402 | ||
1403 | for (start, end) in rejections { | |
1404 | let count = end - start; | |
1405 | if start != len { | |
1406 | // SAFETY: per Searcher::next: | |
1407 | // | |
1408 | // The stream of Match and Reject values up to a Done will | |
1409 | // contain index ranges that are adjacent, non-overlapping, | |
1410 | // covering the whole haystack, and laying on utf8 | |
1411 | // boundaries. | |
1412 | unsafe { | |
1413 | ptr::copy(ptr.add(start), ptr.add(len), count); | |
1414 | } | |
1415 | } | |
1416 | len += count; | |
1417 | } | |
6a06907d | 1418 | |
6a06907d | 1419 | unsafe { |
17df50a5 | 1420 | self.vec.set_len(len); |
6a06907d XL |
1421 | } |
1422 | } | |
1423 | ||
3b2f2976 XL |
1424 | /// Retains only the characters specified by the predicate. |
1425 | /// | |
1426 | /// In other words, remove all characters `c` such that `f(c)` returns `false`. | |
48663c56 XL |
1427 | /// This method operates in place, visiting each character exactly once in the |
1428 | /// original order, and preserves the order of the retained characters. | |
3b2f2976 XL |
1429 | /// |
1430 | /// # Examples | |
1431 | /// | |
1432 | /// ``` | |
3b2f2976 XL |
1433 | /// let mut s = String::from("f_o_ob_ar"); |
1434 | /// | |
1435 | /// s.retain(|c| c != '_'); | |
1436 | /// | |
1437 | /// assert_eq!(s, "foobar"); | |
1438 | /// ``` | |
48663c56 | 1439 | /// |
94222f64 XL |
1440 | /// Because the elements are visited exactly once in the original order, |
1441 | /// external state may be used to decide which elements to keep. | |
48663c56 XL |
1442 | /// |
1443 | /// ``` | |
1444 | /// let mut s = String::from("abcde"); | |
1445 | /// let keep = [false, true, true, false, true]; | |
94222f64 XL |
1446 | /// let mut iter = keep.iter(); |
1447 | /// s.retain(|_| *iter.next().unwrap()); | |
48663c56 XL |
1448 | /// assert_eq!(s, "bce"); |
1449 | /// ``` | |
3b2f2976 | 1450 | #[inline] |
0531ce1d | 1451 | #[stable(feature = "string_retain", since = "1.26.0")] |
3b2f2976 | 1452 | pub fn retain<F>(&mut self, mut f: F) |
dfeec247 XL |
1453 | where |
1454 | F: FnMut(char) -> bool, | |
3b2f2976 | 1455 | { |
cdc7bbd5 XL |
1456 | struct SetLenOnDrop<'a> { |
1457 | s: &'a mut String, | |
1458 | idx: usize, | |
1459 | del_bytes: usize, | |
1460 | } | |
3b2f2976 | 1461 | |
cdc7bbd5 XL |
1462 | impl<'a> Drop for SetLenOnDrop<'a> { |
1463 | fn drop(&mut self) { | |
1464 | let new_len = self.idx - self.del_bytes; | |
1465 | debug_assert!(new_len <= self.s.len()); | |
1466 | unsafe { self.s.vec.set_len(new_len) }; | |
1467 | } | |
29967ef6 XL |
1468 | } |
1469 | ||
cdc7bbd5 XL |
1470 | let len = self.len(); |
1471 | let mut guard = SetLenOnDrop { s: self, idx: 0, del_bytes: 0 }; | |
1472 | ||
1473 | while guard.idx < len { | |
923072b8 FG |
1474 | let ch = |
1475 | // SAFETY: `guard.idx` is positive-or-zero and less that len so the `get_unchecked` | |
1476 | // is in bound. `self` is valid UTF-8 like string and the returned slice starts at | |
1477 | // a unicode code point so the `Chars` always return one character. | |
1478 | unsafe { guard.s.get_unchecked(guard.idx..len).chars().next().unwrap_unchecked() }; | |
3b2f2976 XL |
1479 | let ch_len = ch.len_utf8(); |
1480 | ||
1481 | if !f(ch) { | |
cdc7bbd5 XL |
1482 | guard.del_bytes += ch_len; |
1483 | } else if guard.del_bytes > 0 { | |
923072b8 FG |
1484 | // SAFETY: `guard.idx` is in bound and `guard.del_bytes` represent the number of |
1485 | // bytes that are erased from the string so the resulting `guard.idx - | |
1486 | // guard.del_bytes` always represent a valid unicode code point. | |
1487 | // | |
1488 | // `guard.del_bytes` >= `ch.len_utf8()`, so taking a slice with `ch.len_utf8()` len | |
1489 | // is safe. | |
1490 | ch.encode_utf8(unsafe { | |
1491 | crate::slice::from_raw_parts_mut( | |
1492 | guard.s.as_mut_ptr().add(guard.idx - guard.del_bytes), | |
1493 | ch.len_utf8(), | |
1494 | ) | |
1495 | }); | |
3b2f2976 XL |
1496 | } |
1497 | ||
1498 | // Point idx to the next char | |
cdc7bbd5 | 1499 | guard.idx += ch_len; |
3b2f2976 XL |
1500 | } |
1501 | ||
cdc7bbd5 | 1502 | drop(guard); |
3b2f2976 XL |
1503 | } |
1504 | ||
9cc50fc6 | 1505 | /// Inserts a character into this `String` at a byte position. |
1a4d82fc | 1506 | /// |
3dfed10e | 1507 | /// This is an *O*(*n*) operation as it requires copying every element in the |
1a4d82fc JJ |
1508 | /// buffer. |
1509 | /// | |
1510 | /// # Panics | |
1511 | /// | |
9cc50fc6 SL |
1512 | /// Panics if `idx` is larger than the `String`'s length, or if it does not |
1513 | /// lie on a [`char`] boundary. | |
1514 | /// | |
9cc50fc6 SL |
1515 | /// # Examples |
1516 | /// | |
1517 | /// Basic usage: | |
1518 | /// | |
1519 | /// ``` | |
1520 | /// let mut s = String::with_capacity(3); | |
1521 | /// | |
1522 | /// s.insert(0, 'f'); | |
1523 | /// s.insert(1, 'o'); | |
1524 | /// s.insert(2, 'o'); | |
1525 | /// | |
1526 | /// assert_eq!("foo", s); | |
1527 | /// ``` | |
17df50a5 | 1528 | #[cfg(not(no_global_oom_handling))] |
85aaf69f SL |
1529 | #[inline] |
1530 | #[stable(feature = "rust1", since = "1.0.0")] | |
1531 | pub fn insert(&mut self, idx: usize, ch: char) { | |
1a4d82fc | 1532 | assert!(self.is_char_boundary(idx)); |
c30ab7b3 SL |
1533 | let mut bits = [0; 4]; |
1534 | let bits = ch.encode_utf8(&mut bits).as_bytes(); | |
5bcae85e SL |
1535 | |
1536 | unsafe { | |
c30ab7b3 | 1537 | self.insert_bytes(idx, bits); |
5bcae85e SL |
1538 | } |
1539 | } | |
1540 | ||
17df50a5 | 1541 | #[cfg(not(no_global_oom_handling))] |
5bcae85e SL |
1542 | unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) { |
1543 | let len = self.len(); | |
1544 | let amt = bytes.len(); | |
54a0048b | 1545 | self.vec.reserve(amt); |
1a4d82fc | 1546 | |
f035d41b XL |
1547 | unsafe { |
1548 | ptr::copy(self.vec.as_ptr().add(idx), self.vec.as_mut_ptr().add(idx + amt), len - idx); | |
136023e0 | 1549 | ptr::copy_nonoverlapping(bytes.as_ptr(), self.vec.as_mut_ptr().add(idx), amt); |
f035d41b XL |
1550 | self.vec.set_len(len + amt); |
1551 | } | |
5bcae85e SL |
1552 | } |
1553 | ||
1554 | /// Inserts a string slice into this `String` at a byte position. | |
1555 | /// | |
3dfed10e | 1556 | /// This is an *O*(*n*) operation as it requires copying every element in the |
5bcae85e SL |
1557 | /// buffer. |
1558 | /// | |
1559 | /// # Panics | |
1560 | /// | |
1561 | /// Panics if `idx` is larger than the `String`'s length, or if it does not | |
1562 | /// lie on a [`char`] boundary. | |
1563 | /// | |
5bcae85e SL |
1564 | /// # Examples |
1565 | /// | |
1566 | /// Basic usage: | |
1567 | /// | |
1568 | /// ``` | |
5bcae85e SL |
1569 | /// let mut s = String::from("bar"); |
1570 | /// | |
1571 | /// s.insert_str(0, "foo"); | |
1572 | /// | |
1573 | /// assert_eq!("foobar", s); | |
1574 | /// ``` | |
17df50a5 | 1575 | #[cfg(not(no_global_oom_handling))] |
5bcae85e | 1576 | #[inline] |
32a655c1 | 1577 | #[stable(feature = "insert_str", since = "1.16.0")] |
5bcae85e | 1578 | pub fn insert_str(&mut self, idx: usize, string: &str) { |
5bcae85e SL |
1579 | assert!(self.is_char_boundary(idx)); |
1580 | ||
1a4d82fc | 1581 | unsafe { |
5bcae85e | 1582 | self.insert_bytes(idx, string.as_bytes()); |
1a4d82fc JJ |
1583 | } |
1584 | } | |
1585 | ||
9cc50fc6 | 1586 | /// Returns a mutable reference to the contents of this `String`. |
1a4d82fc | 1587 | /// |
9cc50fc6 SL |
1588 | /// # Safety |
1589 | /// | |
3c0e092e XL |
1590 | /// This function is unsafe because the returned `&mut Vec` allows writing |
1591 | /// bytes which are not valid UTF-8. If this constraint is violated, using | |
1592 | /// the original `String` after dropping the `&mut Vec` may violate memory | |
1593 | /// safety, as the rest of the standard library assumes that `String`s are | |
1594 | /// valid UTF-8. | |
1a4d82fc JJ |
1595 | /// |
1596 | /// # Examples | |
1597 | /// | |
9cc50fc6 SL |
1598 | /// Basic usage: |
1599 | /// | |
1a4d82fc | 1600 | /// ``` |
62682a34 | 1601 | /// let mut s = String::from("hello"); |
9cc50fc6 | 1602 | /// |
1a4d82fc JJ |
1603 | /// unsafe { |
1604 | /// let vec = s.as_mut_vec(); | |
9cc50fc6 SL |
1605 | /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]); |
1606 | /// | |
1a4d82fc JJ |
1607 | /// vec.reverse(); |
1608 | /// } | |
c34b1796 | 1609 | /// assert_eq!(s, "olleh"); |
1a4d82fc | 1610 | /// ``` |
85aaf69f SL |
1611 | #[inline] |
1612 | #[stable(feature = "rust1", since = "1.0.0")] | |
1613 | pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> { | |
1a4d82fc JJ |
1614 | &mut self.vec |
1615 | } | |
1616 | ||
60c5eb7d | 1617 | /// Returns the length of this `String`, in bytes, not [`char`]s or |
94222f64 | 1618 | /// graphemes. In other words, it might not be what a human considers the |
60c5eb7d | 1619 | /// length of the string. |
1a4d82fc JJ |
1620 | /// |
1621 | /// # Examples | |
1622 | /// | |
9cc50fc6 SL |
1623 | /// Basic usage: |
1624 | /// | |
1a4d82fc | 1625 | /// ``` |
9cc50fc6 | 1626 | /// let a = String::from("foo"); |
1a4d82fc | 1627 | /// assert_eq!(a.len(), 3); |
60c5eb7d XL |
1628 | /// |
1629 | /// let fancy_f = String::from("ƒoo"); | |
1630 | /// assert_eq!(fancy_f.len(), 4); | |
1631 | /// assert_eq!(fancy_f.chars().count(), 3); | |
1a4d82fc JJ |
1632 | /// ``` |
1633 | #[inline] | |
3c0e092e | 1634 | #[must_use] |
85aaf69f | 1635 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
1636 | pub fn len(&self) -> usize { |
1637 | self.vec.len() | |
1638 | } | |
1a4d82fc | 1639 | |
9fa01778 | 1640 | /// Returns `true` if this `String` has a length of zero, and `false` otherwise. |
1a4d82fc JJ |
1641 | /// |
1642 | /// # Examples | |
1643 | /// | |
9cc50fc6 SL |
1644 | /// Basic usage: |
1645 | /// | |
1a4d82fc JJ |
1646 | /// ``` |
1647 | /// let mut v = String::new(); | |
1648 | /// assert!(v.is_empty()); | |
9cc50fc6 | 1649 | /// |
1a4d82fc JJ |
1650 | /// v.push('a'); |
1651 | /// assert!(!v.is_empty()); | |
1652 | /// ``` | |
85aaf69f | 1653 | #[inline] |
3c0e092e | 1654 | #[must_use] |
85aaf69f | 1655 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
1656 | pub fn is_empty(&self) -> bool { |
1657 | self.len() == 0 | |
1658 | } | |
1a4d82fc | 1659 | |
fc512014 | 1660 | /// Splits the string into two at the given byte index. |
476ff2be | 1661 | /// |
8bb4bdeb XL |
1662 | /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and |
1663 | /// the returned `String` contains bytes `[at, len)`. `at` must be on the | |
1664 | /// boundary of a UTF-8 code point. | |
476ff2be | 1665 | /// |
8bb4bdeb | 1666 | /// Note that the capacity of `self` does not change. |
476ff2be SL |
1667 | /// |
1668 | /// # Panics | |
1669 | /// | |
8bb4bdeb | 1670 | /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last |
476ff2be SL |
1671 | /// code point of the string. |
1672 | /// | |
1673 | /// # Examples | |
1674 | /// | |
1675 | /// ``` | |
476ff2be SL |
1676 | /// # fn main() { |
1677 | /// let mut hello = String::from("Hello, World!"); | |
1678 | /// let world = hello.split_off(7); | |
1679 | /// assert_eq!(hello, "Hello, "); | |
1680 | /// assert_eq!(world, "World!"); | |
1681 | /// # } | |
1682 | /// ``` | |
17df50a5 | 1683 | #[cfg(not(no_global_oom_handling))] |
476ff2be | 1684 | #[inline] |
32a655c1 | 1685 | #[stable(feature = "string_split_off", since = "1.16.0")] |
ba9703b0 | 1686 | #[must_use = "use `.truncate()` if you don't need the other half"] |
8bb4bdeb XL |
1687 | pub fn split_off(&mut self, at: usize) -> String { |
1688 | assert!(self.is_char_boundary(at)); | |
1689 | let other = self.vec.split_off(at); | |
476ff2be SL |
1690 | unsafe { String::from_utf8_unchecked(other) } |
1691 | } | |
1692 | ||
9cc50fc6 SL |
1693 | /// Truncates this `String`, removing all contents. |
1694 | /// | |
1695 | /// While this means the `String` will have a length of zero, it does not | |
1696 | /// touch its capacity. | |
1a4d82fc JJ |
1697 | /// |
1698 | /// # Examples | |
1699 | /// | |
9cc50fc6 SL |
1700 | /// Basic usage: |
1701 | /// | |
1a4d82fc | 1702 | /// ``` |
9cc50fc6 SL |
1703 | /// let mut s = String::from("foo"); |
1704 | /// | |
1a4d82fc | 1705 | /// s.clear(); |
9cc50fc6 | 1706 | /// |
1a4d82fc | 1707 | /// assert!(s.is_empty()); |
9cc50fc6 SL |
1708 | /// assert_eq!(0, s.len()); |
1709 | /// assert_eq!(3, s.capacity()); | |
1a4d82fc JJ |
1710 | /// ``` |
1711 | #[inline] | |
85aaf69f | 1712 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1713 | pub fn clear(&mut self) { |
1714 | self.vec.clear() | |
1715 | } | |
d9579d0f | 1716 | |
5099ac24 FG |
1717 | /// Removes the specified range from the string in bulk, returning all |
1718 | /// removed characters as an iterator. | |
9cc50fc6 | 1719 | /// |
5099ac24 FG |
1720 | /// The returned iterator keeps a mutable borrow on the string to optimize |
1721 | /// its implementation. | |
d9579d0f AL |
1722 | /// |
1723 | /// # Panics | |
1724 | /// | |
9cc50fc6 SL |
1725 | /// Panics if the starting point or end point do not lie on a [`char`] |
1726 | /// boundary, or if they're out of bounds. | |
1727 | /// | |
5099ac24 FG |
1728 | /// # Leaking |
1729 | /// | |
1730 | /// If the returned iterator goes out of scope without being dropped (due to | |
1731 | /// [`core::mem::forget`], for example), the string may still contain a copy | |
1732 | /// of any drained characters, or may have lost characters arbitrarily, | |
1733 | /// including characters outside the range. | |
1734 | /// | |
d9579d0f AL |
1735 | /// # Examples |
1736 | /// | |
9cc50fc6 SL |
1737 | /// Basic usage: |
1738 | /// | |
d9579d0f | 1739 | /// ``` |
d9579d0f AL |
1740 | /// let mut s = String::from("α is alpha, β is beta"); |
1741 | /// let beta_offset = s.find('β').unwrap_or(s.len()); | |
1742 | /// | |
1743 | /// // Remove the range up until the β from the string | |
1744 | /// let t: String = s.drain(..beta_offset).collect(); | |
1745 | /// assert_eq!(t, "α is alpha, "); | |
1746 | /// assert_eq!(s, "β is beta"); | |
1747 | /// | |
5099ac24 | 1748 | /// // A full range clears the string, like `clear()` does |
d9579d0f AL |
1749 | /// s.drain(..); |
1750 | /// assert_eq!(s, ""); | |
1751 | /// ``` | |
92a42be0 | 1752 | #[stable(feature = "drain", since = "1.6.0")] |
9fa01778 | 1753 | pub fn drain<R>(&mut self, range: R) -> Drain<'_> |
dfeec247 XL |
1754 | where |
1755 | R: RangeBounds<usize>, | |
92a42be0 | 1756 | { |
d9579d0f AL |
1757 | // Memory safety |
1758 | // | |
1759 | // The String version of Drain does not have the memory safety issues | |
1760 | // of the vector version. The data is just plain bytes. | |
1761 | // Because the range removal happens in Drop, if the Drain iterator is leaked, | |
1762 | // the removal will not happen. | |
6a06907d | 1763 | let Range { start, end } = slice::range(range, ..self.len()); |
1b1a35ee XL |
1764 | assert!(self.is_char_boundary(start)); |
1765 | assert!(self.is_char_boundary(end)); | |
d9579d0f AL |
1766 | |
1767 | // Take out two simultaneous borrows. The &mut String won't be accessed | |
1768 | // until iteration is over, in Drop. | |
1769 | let self_ptr = self as *mut _; | |
6a06907d | 1770 | // SAFETY: `slice::range` and `is_char_boundary` do the appropriate bounds checks. |
1b1a35ee | 1771 | let chars_iter = unsafe { self.get_unchecked(start..end) }.chars(); |
d9579d0f | 1772 | |
dfeec247 | 1773 | Drain { start, end, iter: chars_iter, string: self_ptr } |
d9579d0f | 1774 | } |
c1a9b12d | 1775 | |
83c7162d | 1776 | /// Removes the specified range in the string, |
ea8adc8c XL |
1777 | /// and replaces it with the given string. |
1778 | /// The given string doesn't need to be the same length as the range. | |
7cac9316 | 1779 | /// |
7cac9316 XL |
1780 | /// # Panics |
1781 | /// | |
1782 | /// Panics if the starting point or end point do not lie on a [`char`] | |
1783 | /// boundary, or if they're out of bounds. | |
1784 | /// | |
7cac9316 XL |
1785 | /// # Examples |
1786 | /// | |
1787 | /// Basic usage: | |
1788 | /// | |
1789 | /// ``` | |
7cac9316 XL |
1790 | /// let mut s = String::from("α is alpha, β is beta"); |
1791 | /// let beta_offset = s.find('β').unwrap_or(s.len()); | |
1792 | /// | |
1793 | /// // Replace the range up until the β from the string | |
83c7162d | 1794 | /// s.replace_range(..beta_offset, "Α is capital alpha; "); |
7cac9316 XL |
1795 | /// assert_eq!(s, "Α is capital alpha; β is beta"); |
1796 | /// ``` | |
17df50a5 | 1797 | #[cfg(not(no_global_oom_handling))] |
83c7162d XL |
1798 | #[stable(feature = "splice", since = "1.27.0")] |
1799 | pub fn replace_range<R>(&mut self, range: R, replace_with: &str) | |
dfeec247 XL |
1800 | where |
1801 | R: RangeBounds<usize>, | |
7cac9316 XL |
1802 | { |
1803 | // Memory safety | |
1804 | // | |
83c7162d | 1805 | // Replace_range does not have the memory safety issues of a vector Splice. |
7cac9316 | 1806 | // of the vector version. The data is just plain bytes. |
ea8adc8c | 1807 | |
5869c6ff XL |
1808 | // WARNING: Inlining this variable would be unsound (#81138) |
1809 | let start = range.start_bound(); | |
1810 | match start { | |
dfeec247 XL |
1811 | Included(&n) => assert!(self.is_char_boundary(n)), |
1812 | Excluded(&n) => assert!(self.is_char_boundary(n + 1)), | |
1813 | Unbounded => {} | |
7cac9316 | 1814 | }; |
5869c6ff XL |
1815 | // WARNING: Inlining this variable would be unsound (#81138) |
1816 | let end = range.end_bound(); | |
1817 | match end { | |
dfeec247 XL |
1818 | Included(&n) => assert!(self.is_char_boundary(n + 1)), |
1819 | Excluded(&n) => assert!(self.is_char_boundary(n)), | |
1820 | Unbounded => {} | |
7cac9316 XL |
1821 | }; |
1822 | ||
5869c6ff XL |
1823 | // Using `range` again would be unsound (#81138) |
1824 | // We assume the bounds reported by `range` remain the same, but | |
1825 | // an adversarial implementation could change between calls | |
1826 | unsafe { self.as_mut_vec() }.splice((start, end), replace_with.bytes()); | |
7cac9316 XL |
1827 | } |
1828 | ||
c295e0f8 | 1829 | /// Converts this `String` into a <code>[Box]<[str]></code>. |
9cc50fc6 SL |
1830 | /// |
1831 | /// This will drop any excess capacity. | |
1832 | /// | |
c295e0f8 | 1833 | /// [str]: prim@str "str" |
3b2f2976 | 1834 | /// |
9cc50fc6 SL |
1835 | /// # Examples |
1836 | /// | |
1837 | /// Basic usage: | |
1838 | /// | |
1839 | /// ``` | |
1840 | /// let s = String::from("hello"); | |
c1a9b12d | 1841 | /// |
9cc50fc6 SL |
1842 | /// let b = s.into_boxed_str(); |
1843 | /// ``` | |
17df50a5 | 1844 | #[cfg(not(no_global_oom_handling))] |
e9174d1e | 1845 | #[stable(feature = "box_str", since = "1.4.0")] |
c295e0f8 | 1846 | #[must_use = "`self` will be dropped if the result is not used"] |
83c7162d | 1847 | #[inline] |
e9174d1e | 1848 | pub fn into_boxed_str(self) -> Box<str> { |
c1a9b12d | 1849 | let slice = self.vec.into_boxed_slice(); |
041b39d2 | 1850 | unsafe { from_boxed_utf8_unchecked(slice) } |
c1a9b12d | 1851 | } |
2b03887a FG |
1852 | |
1853 | /// Consumes and leaks the `String`, returning a mutable reference to the contents, | |
1854 | /// `&'static mut str`. | |
1855 | /// | |
1856 | /// This is mainly useful for data that lives for the remainder of | |
1857 | /// the program's life. Dropping the returned reference will cause a memory | |
1858 | /// leak. | |
1859 | /// | |
1860 | /// It does not reallocate or shrink the `String`, | |
1861 | /// so the leaked allocation may include unused capacity that is not part | |
1862 | /// of the returned slice. | |
1863 | /// | |
1864 | /// # Examples | |
1865 | /// | |
1866 | /// Simple usage: | |
1867 | /// | |
1868 | /// ``` | |
1869 | /// #![feature(string_leak)] | |
1870 | /// | |
1871 | /// let x = String::from("bucket"); | |
1872 | /// let static_ref: &'static mut str = x.leak(); | |
1873 | /// assert_eq!(static_ref, "bucket"); | |
1874 | /// ``` | |
1875 | #[unstable(feature = "string_leak", issue = "102929")] | |
1876 | #[inline] | |
1877 | pub fn leak(self) -> &'static mut str { | |
1878 | let slice = self.vec.leak(); | |
1879 | unsafe { from_utf8_unchecked_mut(slice) } | |
1880 | } | |
1a4d82fc JJ |
1881 | } |
1882 | ||
1883 | impl FromUtf8Error { | |
cc61c64b XL |
1884 | /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`. |
1885 | /// | |
1886 | /// # Examples | |
1887 | /// | |
1888 | /// Basic usage: | |
1889 | /// | |
1890 | /// ``` | |
cc61c64b XL |
1891 | /// // some invalid bytes, in a vector |
1892 | /// let bytes = vec![0, 159]; | |
1893 | /// | |
1894 | /// let value = String::from_utf8(bytes); | |
1895 | /// | |
1896 | /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes()); | |
1897 | /// ``` | |
c295e0f8 | 1898 | #[must_use] |
0531ce1d | 1899 | #[stable(feature = "from_utf8_error_as_bytes", since = "1.26.0")] |
cc61c64b XL |
1900 | pub fn as_bytes(&self) -> &[u8] { |
1901 | &self.bytes[..] | |
1902 | } | |
1903 | ||
92a42be0 SL |
1904 | /// Returns the bytes that were attempted to convert to a `String`. |
1905 | /// | |
1906 | /// This method is carefully constructed to avoid allocation. It will | |
1907 | /// consume the error, moving out the bytes, so that a copy of the bytes | |
1908 | /// does not need to be made. | |
1909 | /// | |
1910 | /// # Examples | |
1911 | /// | |
1912 | /// Basic usage: | |
1913 | /// | |
1914 | /// ``` | |
1915 | /// // some invalid bytes, in a vector | |
1916 | /// let bytes = vec![0, 159]; | |
1917 | /// | |
1918 | /// let value = String::from_utf8(bytes); | |
1919 | /// | |
1920 | /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes()); | |
1921 | /// ``` | |
c295e0f8 | 1922 | #[must_use = "`self` will be dropped if the result is not used"] |
85aaf69f | 1923 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
1924 | pub fn into_bytes(self) -> Vec<u8> { |
1925 | self.bytes | |
1926 | } | |
1a4d82fc | 1927 | |
92a42be0 SL |
1928 | /// Fetch a `Utf8Error` to get more details about the conversion failure. |
1929 | /// | |
1930 | /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may | |
1931 | /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's | |
1932 | /// an analogue to `FromUtf8Error`. See its documentation for more details | |
1933 | /// on using it. | |
1934 | /// | |
c295e0f8 XL |
1935 | /// [`std::str`]: core::str "std::str" |
1936 | /// [`&str`]: prim@str "&str" | |
92a42be0 SL |
1937 | /// |
1938 | /// # Examples | |
1939 | /// | |
1940 | /// Basic usage: | |
1941 | /// | |
1942 | /// ``` | |
1943 | /// // some invalid bytes, in a vector | |
1944 | /// let bytes = vec![0, 159]; | |
1945 | /// | |
1946 | /// let error = String::from_utf8(bytes).unwrap_err().utf8_error(); | |
1947 | /// | |
1948 | /// // the first byte is invalid here | |
1949 | /// assert_eq!(1, error.valid_up_to()); | |
1950 | /// ``` | |
3c0e092e | 1951 | #[must_use] |
85aaf69f | 1952 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
1953 | pub fn utf8_error(&self) -> Utf8Error { |
1954 | self.error | |
1955 | } | |
1a4d82fc JJ |
1956 | } |
1957 | ||
85aaf69f SL |
1958 | #[stable(feature = "rust1", since = "1.0.0")] |
1959 | impl fmt::Display for FromUtf8Error { | |
9fa01778 | 1960 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
85aaf69f | 1961 | fmt::Display::fmt(&self.error, f) |
1a4d82fc JJ |
1962 | } |
1963 | } | |
1964 | ||
85aaf69f SL |
1965 | #[stable(feature = "rust1", since = "1.0.0")] |
1966 | impl fmt::Display for FromUtf16Error { | |
9fa01778 | 1967 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
85aaf69f | 1968 | fmt::Display::fmt("invalid utf-16: lone surrogate found", f) |
1a4d82fc JJ |
1969 | } |
1970 | } | |
1971 | ||
f2b60f7d FG |
1972 | #[stable(feature = "rust1", since = "1.0.0")] |
1973 | impl Error for FromUtf8Error { | |
1974 | #[allow(deprecated)] | |
1975 | fn description(&self) -> &str { | |
1976 | "invalid utf-8" | |
1977 | } | |
1978 | } | |
1979 | ||
f2b60f7d FG |
1980 | #[stable(feature = "rust1", since = "1.0.0")] |
1981 | impl Error for FromUtf16Error { | |
1982 | #[allow(deprecated)] | |
1983 | fn description(&self) -> &str { | |
1984 | "invalid utf-16" | |
1985 | } | |
1986 | } | |
1987 | ||
17df50a5 | 1988 | #[cfg(not(no_global_oom_handling))] |
b039eaaf SL |
1989 | #[stable(feature = "rust1", since = "1.0.0")] |
1990 | impl Clone for String { | |
1991 | fn clone(&self) -> Self { | |
1992 | String { vec: self.vec.clone() } | |
1993 | } | |
1994 | ||
1995 | fn clone_from(&mut self, source: &Self) { | |
1996 | self.vec.clone_from(&source.vec); | |
1997 | } | |
1998 | } | |
1999 | ||
17df50a5 | 2000 | #[cfg(not(no_global_oom_handling))] |
85aaf69f | 2001 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 2002 | impl FromIterator<char> for String { |
54a0048b | 2003 | fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String { |
1a4d82fc | 2004 | let mut buf = String::new(); |
54a0048b | 2005 | buf.extend(iter); |
1a4d82fc JJ |
2006 | buf |
2007 | } | |
2008 | } | |
2009 | ||
17df50a5 | 2010 | #[cfg(not(no_global_oom_handling))] |
8bb4bdeb XL |
2011 | #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")] |
2012 | impl<'a> FromIterator<&'a char> for String { | |
2013 | fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String { | |
2014 | let mut buf = String::new(); | |
2015 | buf.extend(iter); | |
2016 | buf | |
2017 | } | |
2018 | } | |
2019 | ||
17df50a5 | 2020 | #[cfg(not(no_global_oom_handling))] |
85aaf69f | 2021 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 2022 | impl<'a> FromIterator<&'a str> for String { |
54a0048b | 2023 | fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String { |
e9174d1e | 2024 | let mut buf = String::new(); |
54a0048b | 2025 | buf.extend(iter); |
e9174d1e SL |
2026 | buf |
2027 | } | |
2028 | } | |
2029 | ||
17df50a5 | 2030 | #[cfg(not(no_global_oom_handling))] |
e9174d1e SL |
2031 | #[stable(feature = "extend_string", since = "1.4.0")] |
2032 | impl FromIterator<String> for String { | |
54a0048b | 2033 | fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String { |
0731742a XL |
2034 | let mut iterator = iter.into_iter(); |
2035 | ||
2036 | // Because we're iterating over `String`s, we can avoid at least | |
2037 | // one allocation by getting the first string from the iterator | |
2038 | // and appending to it all the subsequent strings. | |
2039 | match iterator.next() { | |
2040 | None => String::new(), | |
2041 | Some(mut buf) => { | |
2042 | buf.extend(iterator); | |
2043 | buf | |
2044 | } | |
2045 | } | |
1a4d82fc JJ |
2046 | } |
2047 | } | |
2048 | ||
17df50a5 | 2049 | #[cfg(not(no_global_oom_handling))] |
f035d41b XL |
2050 | #[stable(feature = "box_str2", since = "1.45.0")] |
2051 | impl FromIterator<Box<str>> for String { | |
2052 | fn from_iter<I: IntoIterator<Item = Box<str>>>(iter: I) -> String { | |
2053 | let mut buf = String::new(); | |
2054 | buf.extend(iter); | |
2055 | buf | |
2056 | } | |
2057 | } | |
2058 | ||
17df50a5 | 2059 | #[cfg(not(no_global_oom_handling))] |
7cac9316 XL |
2060 | #[stable(feature = "herd_cows", since = "1.19.0")] |
2061 | impl<'a> FromIterator<Cow<'a, str>> for String { | |
2062 | fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> String { | |
0731742a XL |
2063 | let mut iterator = iter.into_iter(); |
2064 | ||
2065 | // Because we're iterating over CoWs, we can (potentially) avoid at least | |
2066 | // one allocation by getting the first item and appending to it all the | |
2067 | // subsequent items. | |
2068 | match iterator.next() { | |
2069 | None => String::new(), | |
2070 | Some(cow) => { | |
2071 | let mut buf = cow.into_owned(); | |
2072 | buf.extend(iterator); | |
2073 | buf | |
2074 | } | |
2075 | } | |
7cac9316 XL |
2076 | } |
2077 | } | |
2078 | ||
17df50a5 | 2079 | #[cfg(not(no_global_oom_handling))] |
bd371182 | 2080 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 2081 | impl Extend<char> for String { |
54a0048b SL |
2082 | fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) { |
2083 | let iterator = iter.into_iter(); | |
1a4d82fc JJ |
2084 | let (lower_bound, _) = iterator.size_hint(); |
2085 | self.reserve(lower_bound); | |
0731742a | 2086 | iterator.for_each(move |c| self.push(c)); |
1a4d82fc | 2087 | } |
f9f354fc XL |
2088 | |
2089 | #[inline] | |
2090 | fn extend_one(&mut self, c: char) { | |
2091 | self.push(c); | |
2092 | } | |
2093 | ||
2094 | #[inline] | |
2095 | fn extend_reserve(&mut self, additional: usize) { | |
2096 | self.reserve(additional); | |
2097 | } | |
1a4d82fc JJ |
2098 | } |
2099 | ||
17df50a5 | 2100 | #[cfg(not(no_global_oom_handling))] |
62682a34 SL |
2101 | #[stable(feature = "extend_ref", since = "1.2.0")] |
2102 | impl<'a> Extend<&'a char> for String { | |
54a0048b SL |
2103 | fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) { |
2104 | self.extend(iter.into_iter().cloned()); | |
62682a34 | 2105 | } |
f9f354fc XL |
2106 | |
2107 | #[inline] | |
2108 | fn extend_one(&mut self, &c: &'a char) { | |
2109 | self.push(c); | |
2110 | } | |
2111 | ||
2112 | #[inline] | |
2113 | fn extend_reserve(&mut self, additional: usize) { | |
2114 | self.reserve(additional); | |
2115 | } | |
62682a34 SL |
2116 | } |
2117 | ||
17df50a5 | 2118 | #[cfg(not(no_global_oom_handling))] |
bd371182 | 2119 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 2120 | impl<'a> Extend<&'a str> for String { |
54a0048b | 2121 | fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) { |
0731742a | 2122 | iter.into_iter().for_each(move |s| self.push_str(s)); |
1a4d82fc | 2123 | } |
f9f354fc XL |
2124 | |
2125 | #[inline] | |
2126 | fn extend_one(&mut self, s: &'a str) { | |
2127 | self.push_str(s); | |
2128 | } | |
1a4d82fc JJ |
2129 | } |
2130 | ||
17df50a5 | 2131 | #[cfg(not(no_global_oom_handling))] |
f035d41b XL |
2132 | #[stable(feature = "box_str2", since = "1.45.0")] |
2133 | impl Extend<Box<str>> for String { | |
2134 | fn extend<I: IntoIterator<Item = Box<str>>>(&mut self, iter: I) { | |
2135 | iter.into_iter().for_each(move |s| self.push_str(&s)); | |
2136 | } | |
2137 | } | |
2138 | ||
17df50a5 | 2139 | #[cfg(not(no_global_oom_handling))] |
e9174d1e SL |
2140 | #[stable(feature = "extend_string", since = "1.4.0")] |
2141 | impl Extend<String> for String { | |
54a0048b | 2142 | fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) { |
0731742a | 2143 | iter.into_iter().for_each(move |s| self.push_str(&s)); |
e9174d1e | 2144 | } |
f9f354fc XL |
2145 | |
2146 | #[inline] | |
2147 | fn extend_one(&mut self, s: String) { | |
2148 | self.push_str(&s); | |
2149 | } | |
e9174d1e SL |
2150 | } |
2151 | ||
17df50a5 | 2152 | #[cfg(not(no_global_oom_handling))] |
7cac9316 XL |
2153 | #[stable(feature = "herd_cows", since = "1.19.0")] |
2154 | impl<'a> Extend<Cow<'a, str>> for String { | |
2155 | fn extend<I: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: I) { | |
0731742a | 2156 | iter.into_iter().for_each(move |s| self.push_str(&s)); |
7cac9316 | 2157 | } |
f9f354fc XL |
2158 | |
2159 | #[inline] | |
2160 | fn extend_one(&mut self, s: Cow<'a, str>) { | |
2161 | self.push_str(&s); | |
2162 | } | |
7cac9316 XL |
2163 | } |
2164 | ||
ba9703b0 XL |
2165 | /// A convenience impl that delegates to the impl for `&str`. |
2166 | /// | |
2167 | /// # Examples | |
2168 | /// | |
2169 | /// ``` | |
2170 | /// assert_eq!(String::from("Hello world").find("world"), Some(6)); | |
2171 | /// ``` | |
dfeec247 XL |
2172 | #[unstable( |
2173 | feature = "pattern", | |
2174 | reason = "API not fully fleshed out and ready to be stabilized", | |
2175 | issue = "27721" | |
2176 | )] | |
c34b1796 AL |
2177 | impl<'a, 'b> Pattern<'a> for &'b String { |
2178 | type Searcher = <&'b str as Pattern<'a>>::Searcher; | |
2179 | ||
2180 | fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher { | |
2181 | self[..].into_searcher(haystack) | |
2182 | } | |
2183 | ||
2184 | #[inline] | |
2185 | fn is_contained_in(self, haystack: &'a str) -> bool { | |
2186 | self[..].is_contained_in(haystack) | |
2187 | } | |
2188 | ||
2189 | #[inline] | |
2190 | fn is_prefix_of(self, haystack: &'a str) -> bool { | |
2191 | self[..].is_prefix_of(haystack) | |
2192 | } | |
ba9703b0 XL |
2193 | |
2194 | #[inline] | |
2195 | fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str> { | |
2196 | self[..].strip_prefix_of(haystack) | |
2197 | } | |
2198 | ||
2199 | #[inline] | |
2200 | fn is_suffix_of(self, haystack: &'a str) -> bool { | |
2201 | self[..].is_suffix_of(haystack) | |
2202 | } | |
2203 | ||
2204 | #[inline] | |
2205 | fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str> { | |
2206 | self[..].strip_suffix_of(haystack) | |
2207 | } | |
c34b1796 AL |
2208 | } |
2209 | ||
85aaf69f | 2210 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
2211 | impl PartialEq for String { |
2212 | #[inline] | |
92a42be0 SL |
2213 | fn eq(&self, other: &String) -> bool { |
2214 | PartialEq::eq(&self[..], &other[..]) | |
2215 | } | |
1a4d82fc | 2216 | #[inline] |
92a42be0 SL |
2217 | fn ne(&self, other: &String) -> bool { |
2218 | PartialEq::ne(&self[..], &other[..]) | |
2219 | } | |
1a4d82fc JJ |
2220 | } |
2221 | ||
2222 | macro_rules! impl_eq { | |
2223 | ($lhs:ty, $rhs: ty) => { | |
85aaf69f | 2224 | #[stable(feature = "rust1", since = "1.0.0")] |
416331ca | 2225 | #[allow(unused_lifetimes)] |
92a42be0 | 2226 | impl<'a, 'b> PartialEq<$rhs> for $lhs { |
1a4d82fc | 2227 | #[inline] |
dfeec247 XL |
2228 | fn eq(&self, other: &$rhs) -> bool { |
2229 | PartialEq::eq(&self[..], &other[..]) | |
2230 | } | |
1a4d82fc | 2231 | #[inline] |
dfeec247 XL |
2232 | fn ne(&self, other: &$rhs) -> bool { |
2233 | PartialEq::ne(&self[..], &other[..]) | |
2234 | } | |
1a4d82fc JJ |
2235 | } |
2236 | ||
85aaf69f | 2237 | #[stable(feature = "rust1", since = "1.0.0")] |
416331ca | 2238 | #[allow(unused_lifetimes)] |
92a42be0 | 2239 | impl<'a, 'b> PartialEq<$lhs> for $rhs { |
1a4d82fc | 2240 | #[inline] |
dfeec247 XL |
2241 | fn eq(&self, other: &$lhs) -> bool { |
2242 | PartialEq::eq(&self[..], &other[..]) | |
2243 | } | |
1a4d82fc | 2244 | #[inline] |
dfeec247 XL |
2245 | fn ne(&self, other: &$lhs) -> bool { |
2246 | PartialEq::ne(&self[..], &other[..]) | |
2247 | } | |
1a4d82fc | 2248 | } |
dfeec247 | 2249 | }; |
1a4d82fc JJ |
2250 | } |
2251 | ||
9346a6ac | 2252 | impl_eq! { String, str } |
1a4d82fc | 2253 | impl_eq! { String, &'a str } |
17df50a5 | 2254 | #[cfg(not(no_global_oom_handling))] |
9346a6ac | 2255 | impl_eq! { Cow<'a, str>, str } |
17df50a5 | 2256 | #[cfg(not(no_global_oom_handling))] |
92a42be0 | 2257 | impl_eq! { Cow<'a, str>, &'b str } |
17df50a5 | 2258 | #[cfg(not(no_global_oom_handling))] |
85aaf69f | 2259 | impl_eq! { Cow<'a, str>, String } |
1a4d82fc | 2260 | |
85aaf69f | 2261 | #[stable(feature = "rust1", since = "1.0.0")] |
94222f64 XL |
2262 | #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] |
2263 | impl const Default for String { | |
9e0c209e | 2264 | /// Creates an empty `String`. |
85aaf69f | 2265 | #[inline] |
1a4d82fc JJ |
2266 | fn default() -> String { |
2267 | String::new() | |
2268 | } | |
2269 | } | |
2270 | ||
85aaf69f SL |
2271 | #[stable(feature = "rust1", since = "1.0.0")] |
2272 | impl fmt::Display for String { | |
2273 | #[inline] | |
9fa01778 | 2274 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
85aaf69f | 2275 | fmt::Display::fmt(&**self, f) |
1a4d82fc JJ |
2276 | } |
2277 | } | |
2278 | ||
85aaf69f SL |
2279 | #[stable(feature = "rust1", since = "1.0.0")] |
2280 | impl fmt::Debug for String { | |
2281 | #[inline] | |
9fa01778 | 2282 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
85aaf69f | 2283 | fmt::Debug::fmt(&**self, f) |
1a4d82fc JJ |
2284 | } |
2285 | } | |
2286 | ||
85aaf69f | 2287 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 2288 | impl hash::Hash for String { |
1a4d82fc | 2289 | #[inline] |
85aaf69f | 2290 | fn hash<H: hash::Hasher>(&self, hasher: &mut H) { |
1a4d82fc JJ |
2291 | (**self).hash(hasher) |
2292 | } | |
2293 | } | |
2294 | ||
8bb4bdeb XL |
2295 | /// Implements the `+` operator for concatenating two strings. |
2296 | /// | |
2297 | /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if | |
2298 | /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on | |
3dfed10e | 2299 | /// every operation, which would lead to *O*(*n*^2) running time when building an *n*-byte string by |
8bb4bdeb XL |
2300 | /// repeated concatenation. |
2301 | /// | |
2302 | /// The string on the right-hand side is only borrowed; its contents are copied into the returned | |
2303 | /// `String`. | |
2304 | /// | |
2305 | /// # Examples | |
2306 | /// | |
2307 | /// Concatenating two `String`s takes the first by value and borrows the second: | |
2308 | /// | |
2309 | /// ``` | |
2310 | /// let a = String::from("hello"); | |
2311 | /// let b = String::from(" world"); | |
2312 | /// let c = a + &b; | |
2313 | /// // `a` is moved and can no longer be used here. | |
2314 | /// ``` | |
2315 | /// | |
2316 | /// If you want to keep using the first `String`, you can clone it and append to the clone instead: | |
2317 | /// | |
2318 | /// ``` | |
2319 | /// let a = String::from("hello"); | |
2320 | /// let b = String::from(" world"); | |
2321 | /// let c = a.clone() + &b; | |
2322 | /// // `a` is still valid here. | |
2323 | /// ``` | |
2324 | /// | |
2325 | /// Concatenating `&str` slices can be done by converting the first to a `String`: | |
2326 | /// | |
2327 | /// ``` | |
2328 | /// let a = "hello"; | |
2329 | /// let b = " world"; | |
2330 | /// let c = a.to_string() + b; | |
2331 | /// ``` | |
17df50a5 | 2332 | #[cfg(not(no_global_oom_handling))] |
bd371182 | 2333 | #[stable(feature = "rust1", since = "1.0.0")] |
9fa01778 | 2334 | impl Add<&str> for String { |
1a4d82fc JJ |
2335 | type Output = String; |
2336 | ||
85aaf69f | 2337 | #[inline] |
1a4d82fc JJ |
2338 | fn add(mut self, other: &str) -> String { |
2339 | self.push_str(other); | |
2340 | self | |
2341 | } | |
2342 | } | |
2343 | ||
8bb4bdeb XL |
2344 | /// Implements the `+=` operator for appending to a `String`. |
2345 | /// | |
b7449926 | 2346 | /// This has the same behavior as the [`push_str`][String::push_str] method. |
17df50a5 | 2347 | #[cfg(not(no_global_oom_handling))] |
5bcae85e | 2348 | #[stable(feature = "stringaddassign", since = "1.12.0")] |
9fa01778 | 2349 | impl AddAssign<&str> for String { |
5bcae85e SL |
2350 | #[inline] |
2351 | fn add_assign(&mut self, other: &str) { | |
2352 | self.push_str(other); | |
2353 | } | |
2354 | } | |
2355 | ||
85aaf69f SL |
2356 | #[stable(feature = "rust1", since = "1.0.0")] |
2357 | impl ops::Index<ops::Range<usize>> for String { | |
1a4d82fc | 2358 | type Output = str; |
c34b1796 | 2359 | |
1a4d82fc | 2360 | #[inline] |
c34b1796 AL |
2361 | fn index(&self, index: ops::Range<usize>) -> &str { |
2362 | &self[..][index] | |
1a4d82fc JJ |
2363 | } |
2364 | } | |
85aaf69f SL |
2365 | #[stable(feature = "rust1", since = "1.0.0")] |
2366 | impl ops::Index<ops::RangeTo<usize>> for String { | |
1a4d82fc | 2367 | type Output = str; |
c34b1796 | 2368 | |
1a4d82fc | 2369 | #[inline] |
c34b1796 AL |
2370 | fn index(&self, index: ops::RangeTo<usize>) -> &str { |
2371 | &self[..][index] | |
1a4d82fc JJ |
2372 | } |
2373 | } | |
85aaf69f SL |
2374 | #[stable(feature = "rust1", since = "1.0.0")] |
2375 | impl ops::Index<ops::RangeFrom<usize>> for String { | |
1a4d82fc | 2376 | type Output = str; |
c34b1796 | 2377 | |
1a4d82fc | 2378 | #[inline] |
c34b1796 AL |
2379 | fn index(&self, index: ops::RangeFrom<usize>) -> &str { |
2380 | &self[..][index] | |
1a4d82fc JJ |
2381 | } |
2382 | } | |
85aaf69f SL |
2383 | #[stable(feature = "rust1", since = "1.0.0")] |
2384 | impl ops::Index<ops::RangeFull> for String { | |
1a4d82fc | 2385 | type Output = str; |
c34b1796 | 2386 | |
1a4d82fc | 2387 | #[inline] |
c34b1796 | 2388 | fn index(&self, _index: ops::RangeFull) -> &str { |
e9174d1e | 2389 | unsafe { str::from_utf8_unchecked(&self.vec) } |
1a4d82fc JJ |
2390 | } |
2391 | } | |
0531ce1d | 2392 | #[stable(feature = "inclusive_range", since = "1.26.0")] |
54a0048b SL |
2393 | impl ops::Index<ops::RangeInclusive<usize>> for String { |
2394 | type Output = str; | |
2395 | ||
2396 | #[inline] | |
2397 | fn index(&self, index: ops::RangeInclusive<usize>) -> &str { | |
2398 | Index::index(&**self, index) | |
2399 | } | |
2400 | } | |
0531ce1d | 2401 | #[stable(feature = "inclusive_range", since = "1.26.0")] |
54a0048b SL |
2402 | impl ops::Index<ops::RangeToInclusive<usize>> for String { |
2403 | type Output = str; | |
2404 | ||
2405 | #[inline] | |
2406 | fn index(&self, index: ops::RangeToInclusive<usize>) -> &str { | |
2407 | Index::index(&**self, index) | |
2408 | } | |
2409 | } | |
1a4d82fc | 2410 | |
7cac9316 | 2411 | #[stable(feature = "derefmut_for_string", since = "1.3.0")] |
c1a9b12d SL |
2412 | impl ops::IndexMut<ops::Range<usize>> for String { |
2413 | #[inline] | |
2414 | fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str { | |
2415 | &mut self[..][index] | |
2416 | } | |
2417 | } | |
7cac9316 | 2418 | #[stable(feature = "derefmut_for_string", since = "1.3.0")] |
c1a9b12d SL |
2419 | impl ops::IndexMut<ops::RangeTo<usize>> for String { |
2420 | #[inline] | |
2421 | fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str { | |
2422 | &mut self[..][index] | |
2423 | } | |
2424 | } | |
7cac9316 | 2425 | #[stable(feature = "derefmut_for_string", since = "1.3.0")] |
c1a9b12d SL |
2426 | impl ops::IndexMut<ops::RangeFrom<usize>> for String { |
2427 | #[inline] | |
2428 | fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str { | |
2429 | &mut self[..][index] | |
2430 | } | |
2431 | } | |
7cac9316 | 2432 | #[stable(feature = "derefmut_for_string", since = "1.3.0")] |
c1a9b12d SL |
2433 | impl ops::IndexMut<ops::RangeFull> for String { |
2434 | #[inline] | |
2435 | fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str { | |
cc61c64b | 2436 | unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) } |
c1a9b12d SL |
2437 | } |
2438 | } | |
0531ce1d | 2439 | #[stable(feature = "inclusive_range", since = "1.26.0")] |
54a0048b SL |
2440 | impl ops::IndexMut<ops::RangeInclusive<usize>> for String { |
2441 | #[inline] | |
2442 | fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str { | |
2443 | IndexMut::index_mut(&mut **self, index) | |
2444 | } | |
2445 | } | |
0531ce1d | 2446 | #[stable(feature = "inclusive_range", since = "1.26.0")] |
54a0048b SL |
2447 | impl ops::IndexMut<ops::RangeToInclusive<usize>> for String { |
2448 | #[inline] | |
2449 | fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str { | |
2450 | IndexMut::index_mut(&mut **self, index) | |
2451 | } | |
2452 | } | |
c1a9b12d | 2453 | |
85aaf69f | 2454 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
2455 | impl ops::Deref for String { |
2456 | type Target = str; | |
2457 | ||
85aaf69f SL |
2458 | #[inline] |
2459 | fn deref(&self) -> &str { | |
e9174d1e | 2460 | unsafe { str::from_utf8_unchecked(&self.vec) } |
1a4d82fc JJ |
2461 | } |
2462 | } | |
2463 | ||
7cac9316 | 2464 | #[stable(feature = "derefmut_for_string", since = "1.3.0")] |
c1a9b12d | 2465 | impl ops::DerefMut for String { |
85aaf69f | 2466 | #[inline] |
c1a9b12d | 2467 | fn deref_mut(&mut self) -> &mut str { |
cc61c64b | 2468 | unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) } |
1a4d82fc JJ |
2469 | } |
2470 | } | |
2471 | ||
74b04a01 | 2472 | /// A type alias for [`Infallible`]. |
92a42be0 | 2473 | /// |
74b04a01 | 2474 | /// This alias exists for backwards compatibility, and may be eventually deprecated. |
92a42be0 | 2475 | /// |
c295e0f8 | 2476 | /// [`Infallible`]: core::convert::Infallible "convert::Infallible" |
b039eaaf | 2477 | #[stable(feature = "str_parse_error", since = "1.5.0")] |
9fa01778 | 2478 | pub type ParseError = core::convert::Infallible; |
bd371182 | 2479 | |
17df50a5 | 2480 | #[cfg(not(no_global_oom_handling))] |
bd371182 | 2481 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 2482 | impl FromStr for String { |
9fa01778 | 2483 | type Err = core::convert::Infallible; |
1a4d82fc | 2484 | #[inline] |
74b04a01 | 2485 | fn from_str(s: &str) -> Result<String, Self::Err> { |
62682a34 | 2486 | Ok(String::from(s)) |
1a4d82fc JJ |
2487 | } |
2488 | } | |
2489 | ||
92a42be0 SL |
2490 | /// A trait for converting a value to a `String`. |
2491 | /// | |
2492 | /// This trait is automatically implemented for any type which implements the | |
2493 | /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly: | |
2494 | /// [`Display`] should be implemented instead, and you get the `ToString` | |
2495 | /// implementation for free. | |
2496 | /// | |
3dfed10e | 2497 | /// [`Display`]: fmt::Display |
6a06907d | 2498 | #[cfg_attr(not(test), rustc_diagnostic_item = "ToString")] |
85aaf69f | 2499 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 2500 | pub trait ToString { |
92a42be0 SL |
2501 | /// Converts the given value to a `String`. |
2502 | /// | |
2503 | /// # Examples | |
2504 | /// | |
2505 | /// Basic usage: | |
2506 | /// | |
2507 | /// ``` | |
2508 | /// let i = 5; | |
2509 | /// let five = String::from("5"); | |
2510 | /// | |
2511 | /// assert_eq!(five, i.to_string()); | |
2512 | /// ``` | |
2c00a5a8 | 2513 | #[rustc_conversion_suggestion] |
85aaf69f | 2514 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
2515 | fn to_string(&self) -> String; |
2516 | } | |
2517 | ||
8bb4bdeb XL |
2518 | /// # Panics |
2519 | /// | |
2520 | /// In this implementation, the `to_string` method panics | |
2521 | /// if the `Display` implementation returns an error. | |
2522 | /// This indicates an incorrect `Display` implementation | |
2523 | /// since `fmt::Write for String` never returns an error itself. | |
17df50a5 | 2524 | #[cfg(not(no_global_oom_handling))] |
85aaf69f SL |
2525 | #[stable(feature = "rust1", since = "1.0.0")] |
2526 | impl<T: fmt::Display + ?Sized> ToString for T { | |
3dfed10e | 2527 | // A common guideline is to not inline generic functions. However, |
29967ef6 XL |
2528 | // removing `#[inline]` from this method causes non-negligible regressions. |
2529 | // See <https://github.com/rust-lang/rust/pull/74852>, the last attempt | |
2530 | // to try to remove it. | |
85aaf69f | 2531 | #[inline] |
54a0048b | 2532 | default fn to_string(&self) -> String { |
1a4d82fc | 2533 | let mut buf = String::new(); |
17df50a5 XL |
2534 | let mut formatter = core::fmt::Formatter::new(&mut buf); |
2535 | // Bypass format_args!() to avoid write_str with zero-length strs | |
2536 | fmt::Display::fmt(self, &mut formatter) | |
dfeec247 | 2537 | .expect("a Display implementation returned an error unexpectedly"); |
1a4d82fc JJ |
2538 | buf |
2539 | } | |
2540 | } | |
2541 | ||
17df50a5 | 2542 | #[cfg(not(no_global_oom_handling))] |
f035d41b XL |
2543 | #[stable(feature = "char_to_string_specialization", since = "1.46.0")] |
2544 | impl ToString for char { | |
2545 | #[inline] | |
2546 | fn to_string(&self) -> String { | |
2547 | String::from(self.encode_utf8(&mut [0; 4])) | |
2548 | } | |
2549 | } | |
2550 | ||
17df50a5 XL |
2551 | #[cfg(not(no_global_oom_handling))] |
2552 | #[stable(feature = "u8_to_string_specialization", since = "1.54.0")] | |
2553 | impl ToString for u8 { | |
2554 | #[inline] | |
2555 | fn to_string(&self) -> String { | |
2556 | let mut buf = String::with_capacity(3); | |
2557 | let mut n = *self; | |
2558 | if n >= 10 { | |
2559 | if n >= 100 { | |
2560 | buf.push((b'0' + n / 100) as char); | |
2561 | n %= 100; | |
2562 | } | |
2563 | buf.push((b'0' + n / 10) as char); | |
2564 | n %= 10; | |
2565 | } | |
2566 | buf.push((b'0' + n) as char); | |
2567 | buf | |
2568 | } | |
2569 | } | |
2570 | ||
2571 | #[cfg(not(no_global_oom_handling))] | |
2572 | #[stable(feature = "i8_to_string_specialization", since = "1.54.0")] | |
2573 | impl ToString for i8 { | |
2574 | #[inline] | |
2575 | fn to_string(&self) -> String { | |
2576 | let mut buf = String::with_capacity(4); | |
2577 | if self.is_negative() { | |
2578 | buf.push('-'); | |
2579 | } | |
2580 | let mut n = self.unsigned_abs(); | |
2581 | if n >= 10 { | |
2582 | if n >= 100 { | |
2583 | buf.push('1'); | |
2584 | n -= 100; | |
2585 | } | |
2586 | buf.push((b'0' + n / 10) as char); | |
2587 | n %= 10; | |
2588 | } | |
2589 | buf.push((b'0' + n) as char); | |
2590 | buf | |
2591 | } | |
2592 | } | |
2593 | ||
2594 | #[cfg(not(no_global_oom_handling))] | |
54a0048b SL |
2595 | #[stable(feature = "str_to_string_specialization", since = "1.9.0")] |
2596 | impl ToString for str { | |
2597 | #[inline] | |
2598 | fn to_string(&self) -> String { | |
2599 | String::from(self) | |
2600 | } | |
2601 | } | |
2602 | ||
17df50a5 | 2603 | #[cfg(not(no_global_oom_handling))] |
8bb4bdeb | 2604 | #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")] |
9fa01778 | 2605 | impl ToString for Cow<'_, str> { |
8bb4bdeb XL |
2606 | #[inline] |
2607 | fn to_string(&self) -> String { | |
2608 | self[..].to_owned() | |
2609 | } | |
2610 | } | |
2611 | ||
17df50a5 | 2612 | #[cfg(not(no_global_oom_handling))] |
8bb4bdeb XL |
2613 | #[stable(feature = "string_to_string_specialization", since = "1.17.0")] |
2614 | impl ToString for String { | |
2615 | #[inline] | |
2616 | fn to_string(&self) -> String { | |
2617 | self.to_owned() | |
2618 | } | |
2619 | } | |
2620 | ||
85aaf69f | 2621 | #[stable(feature = "rust1", since = "1.0.0")] |
c34b1796 | 2622 | impl AsRef<str> for String { |
d9579d0f | 2623 | #[inline] |
c34b1796 AL |
2624 | fn as_ref(&self) -> &str { |
2625 | self | |
2626 | } | |
2627 | } | |
2628 | ||
74b04a01 XL |
2629 | #[stable(feature = "string_as_mut", since = "1.43.0")] |
2630 | impl AsMut<str> for String { | |
2631 | #[inline] | |
2632 | fn as_mut(&mut self) -> &mut str { | |
2633 | self | |
2634 | } | |
2635 | } | |
2636 | ||
bd371182 AL |
2637 | #[stable(feature = "rust1", since = "1.0.0")] |
2638 | impl AsRef<[u8]> for String { | |
2639 | #[inline] | |
2640 | fn as_ref(&self) -> &[u8] { | |
2641 | self.as_bytes() | |
2642 | } | |
2643 | } | |
2644 | ||
17df50a5 | 2645 | #[cfg(not(no_global_oom_handling))] |
c34b1796 | 2646 | #[stable(feature = "rust1", since = "1.0.0")] |
532ac7d7 | 2647 | impl From<&str> for String { |
17df50a5 XL |
2648 | /// Converts a `&str` into a [`String`]. |
2649 | /// | |
2650 | /// The result is allocated on the heap. | |
0bf4aa26 | 2651 | #[inline] |
532ac7d7 | 2652 | fn from(s: &str) -> String { |
54a0048b | 2653 | s.to_owned() |
c34b1796 AL |
2654 | } |
2655 | } | |
2656 | ||
17df50a5 | 2657 | #[cfg(not(no_global_oom_handling))] |
ba9703b0 XL |
2658 | #[stable(feature = "from_mut_str_for_string", since = "1.44.0")] |
2659 | impl From<&mut str> for String { | |
17df50a5 | 2660 | /// Converts a `&mut str` into a [`String`]. |
ba9703b0 XL |
2661 | /// |
2662 | /// The result is allocated on the heap. | |
2663 | #[inline] | |
2664 | fn from(s: &mut str) -> String { | |
2665 | s.to_owned() | |
2666 | } | |
2667 | } | |
2668 | ||
17df50a5 | 2669 | #[cfg(not(no_global_oom_handling))] |
48663c56 XL |
2670 | #[stable(feature = "from_ref_string", since = "1.35.0")] |
2671 | impl From<&String> for String { | |
17df50a5 XL |
2672 | /// Converts a `&String` into a [`String`]. |
2673 | /// | |
2674 | /// This clones `s` and returns the clone. | |
48663c56 XL |
2675 | #[inline] |
2676 | fn from(s: &String) -> String { | |
2677 | s.clone() | |
2678 | } | |
2679 | } | |
2680 | ||
cc61c64b XL |
2681 | // note: test pulls in libstd, which causes errors here |
2682 | #[cfg(not(test))] | |
7cac9316 | 2683 | #[stable(feature = "string_from_box", since = "1.18.0")] |
cc61c64b | 2684 | impl From<Box<str>> for String { |
17df50a5 | 2685 | /// Converts the given boxed `str` slice to a [`String`]. |
a1dfa0c6 XL |
2686 | /// It is notable that the `str` slice is owned. |
2687 | /// | |
2688 | /// # Examples | |
2689 | /// | |
2690 | /// Basic usage: | |
2691 | /// | |
2692 | /// ``` | |
2693 | /// let s1: String = String::from("hello world"); | |
2694 | /// let s2: Box<str> = s1.into_boxed_str(); | |
2695 | /// let s3: String = String::from(s2); | |
2696 | /// | |
2697 | /// assert_eq!("hello world", s3) | |
2698 | /// ``` | |
cc61c64b XL |
2699 | fn from(s: Box<str>) -> String { |
2700 | s.into_string() | |
2701 | } | |
2702 | } | |
2703 | ||
17df50a5 | 2704 | #[cfg(not(no_global_oom_handling))] |
041b39d2 XL |
2705 | #[stable(feature = "box_from_str", since = "1.20.0")] |
2706 | impl From<String> for Box<str> { | |
17df50a5 | 2707 | /// Converts the given [`String`] to a boxed `str` slice that is owned. |
a1dfa0c6 XL |
2708 | /// |
2709 | /// # Examples | |
2710 | /// | |
2711 | /// Basic usage: | |
2712 | /// | |
2713 | /// ``` | |
2714 | /// let s1: String = String::from("hello world"); | |
2715 | /// let s2: Box<str> = Box::from(s1); | |
2716 | /// let s3: String = String::from(s2); | |
2717 | /// | |
2718 | /// assert_eq!("hello world", s3) | |
2719 | /// ``` | |
041b39d2 XL |
2720 | fn from(s: String) -> Box<str> { |
2721 | s.into_boxed_str() | |
cc61c64b XL |
2722 | } |
2723 | } | |
2724 | ||
17df50a5 | 2725 | #[cfg(not(no_global_oom_handling))] |
c30ab7b3 SL |
2726 | #[stable(feature = "string_from_cow_str", since = "1.14.0")] |
2727 | impl<'a> From<Cow<'a, str>> for String { | |
17df50a5 XL |
2728 | /// Converts a clone-on-write string to an owned |
2729 | /// instance of [`String`]. | |
2730 | /// | |
2731 | /// This extracts the owned string, | |
2732 | /// clones the string if it is not already owned. | |
2733 | /// | |
2734 | /// # Example | |
2735 | /// | |
2736 | /// ``` | |
2737 | /// # use std::borrow::Cow; | |
2738 | /// // If the string is not owned... | |
2739 | /// let cow: Cow<str> = Cow::Borrowed("eggplant"); | |
2740 | /// // It will allocate on the heap and copy the string. | |
2741 | /// let owned: String = String::from(cow); | |
2742 | /// assert_eq!(&owned[..], "eggplant"); | |
2743 | /// ``` | |
c30ab7b3 SL |
2744 | fn from(s: Cow<'a, str>) -> String { |
2745 | s.into_owned() | |
2746 | } | |
2747 | } | |
2748 | ||
17df50a5 | 2749 | #[cfg(not(no_global_oom_handling))] |
c34b1796 AL |
2750 | #[stable(feature = "rust1", since = "1.0.0")] |
2751 | impl<'a> From<&'a str> for Cow<'a, str> { | |
17df50a5 | 2752 | /// Converts a string slice into a [`Borrowed`] variant. |
6a06907d XL |
2753 | /// No heap allocation is performed, and the string |
2754 | /// is not copied. | |
2755 | /// | |
2756 | /// # Example | |
2757 | /// | |
2758 | /// ``` | |
2759 | /// # use std::borrow::Cow; | |
2760 | /// assert_eq!(Cow::from("eggplant"), Cow::Borrowed("eggplant")); | |
2761 | /// ``` | |
17df50a5 | 2762 | /// |
c295e0f8 | 2763 | /// [`Borrowed`]: crate::borrow::Cow::Borrowed "borrow::Cow::Borrowed" |
c34b1796 AL |
2764 | #[inline] |
2765 | fn from(s: &'a str) -> Cow<'a, str> { | |
2766 | Cow::Borrowed(s) | |
2767 | } | |
2768 | } | |
2769 | ||
17df50a5 | 2770 | #[cfg(not(no_global_oom_handling))] |
c34b1796 AL |
2771 | #[stable(feature = "rust1", since = "1.0.0")] |
2772 | impl<'a> From<String> for Cow<'a, str> { | |
17df50a5 | 2773 | /// Converts a [`String`] into an [`Owned`] variant. |
6a06907d XL |
2774 | /// No heap allocation is performed, and the string |
2775 | /// is not copied. | |
2776 | /// | |
2777 | /// # Example | |
2778 | /// | |
2779 | /// ``` | |
2780 | /// # use std::borrow::Cow; | |
2781 | /// let s = "eggplant".to_string(); | |
2782 | /// let s2 = "eggplant".to_string(); | |
2783 | /// assert_eq!(Cow::from(s), Cow::<'static, str>::Owned(s2)); | |
2784 | /// ``` | |
17df50a5 | 2785 | /// |
c295e0f8 | 2786 | /// [`Owned`]: crate::borrow::Cow::Owned "borrow::Cow::Owned" |
c34b1796 AL |
2787 | #[inline] |
2788 | fn from(s: String) -> Cow<'a, str> { | |
2789 | Cow::Owned(s) | |
2790 | } | |
2791 | } | |
2792 | ||
17df50a5 | 2793 | #[cfg(not(no_global_oom_handling))] |
94b46f34 XL |
2794 | #[stable(feature = "cow_from_string_ref", since = "1.28.0")] |
2795 | impl<'a> From<&'a String> for Cow<'a, str> { | |
17df50a5 | 2796 | /// Converts a [`String`] reference into a [`Borrowed`] variant. |
6a06907d XL |
2797 | /// No heap allocation is performed, and the string |
2798 | /// is not copied. | |
2799 | /// | |
2800 | /// # Example | |
2801 | /// | |
2802 | /// ``` | |
2803 | /// # use std::borrow::Cow; | |
2804 | /// let s = "eggplant".to_string(); | |
2805 | /// assert_eq!(Cow::from(&s), Cow::Borrowed("eggplant")); | |
2806 | /// ``` | |
17df50a5 | 2807 | /// |
c295e0f8 | 2808 | /// [`Borrowed`]: crate::borrow::Cow::Borrowed "borrow::Cow::Borrowed" |
94b46f34 XL |
2809 | #[inline] |
2810 | fn from(s: &'a String) -> Cow<'a, str> { | |
2811 | Cow::Borrowed(s.as_str()) | |
2812 | } | |
2813 | } | |
2814 | ||
17df50a5 | 2815 | #[cfg(not(no_global_oom_handling))] |
5bcae85e SL |
2816 | #[stable(feature = "cow_str_from_iter", since = "1.12.0")] |
2817 | impl<'a> FromIterator<char> for Cow<'a, str> { | |
2818 | fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> { | |
2819 | Cow::Owned(FromIterator::from_iter(it)) | |
2820 | } | |
2821 | } | |
2822 | ||
17df50a5 | 2823 | #[cfg(not(no_global_oom_handling))] |
5bcae85e SL |
2824 | #[stable(feature = "cow_str_from_iter", since = "1.12.0")] |
2825 | impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> { | |
2826 | fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> { | |
2827 | Cow::Owned(FromIterator::from_iter(it)) | |
2828 | } | |
2829 | } | |
2830 | ||
17df50a5 | 2831 | #[cfg(not(no_global_oom_handling))] |
5bcae85e SL |
2832 | #[stable(feature = "cow_str_from_iter", since = "1.12.0")] |
2833 | impl<'a> FromIterator<String> for Cow<'a, str> { | |
2834 | fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> { | |
2835 | Cow::Owned(FromIterator::from_iter(it)) | |
2836 | } | |
2837 | } | |
2838 | ||
c30ab7b3 SL |
2839 | #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")] |
2840 | impl From<String> for Vec<u8> { | |
17df50a5 | 2841 | /// Converts the given [`String`] to a vector [`Vec`] that holds values of type [`u8`]. |
a1dfa0c6 XL |
2842 | /// |
2843 | /// # Examples | |
2844 | /// | |
2845 | /// Basic usage: | |
2846 | /// | |
2847 | /// ``` | |
2848 | /// let s1 = String::from("hello world"); | |
2849 | /// let v1 = Vec::from(s1); | |
2850 | /// | |
2851 | /// for b in v1 { | |
5e7ed085 | 2852 | /// println!("{b}"); |
a1dfa0c6 XL |
2853 | /// } |
2854 | /// ``` | |
32a655c1 | 2855 | fn from(string: String) -> Vec<u8> { |
c30ab7b3 | 2856 | string.into_bytes() |
c34b1796 AL |
2857 | } |
2858 | } | |
2859 | ||
17df50a5 | 2860 | #[cfg(not(no_global_oom_handling))] |
85aaf69f SL |
2861 | #[stable(feature = "rust1", since = "1.0.0")] |
2862 | impl fmt::Write for String { | |
2863 | #[inline] | |
1a4d82fc JJ |
2864 | fn write_str(&mut self, s: &str) -> fmt::Result { |
2865 | self.push_str(s); | |
2866 | Ok(()) | |
2867 | } | |
d9579d0f AL |
2868 | |
2869 | #[inline] | |
2870 | fn write_char(&mut self, c: char) -> fmt::Result { | |
2871 | self.push(c); | |
2872 | Ok(()) | |
2873 | } | |
2874 | } | |
2875 | ||
2876 | /// A draining iterator for `String`. | |
7453a54e | 2877 | /// |
cc61c64b | 2878 | /// This struct is created by the [`drain`] method on [`String`]. See its |
7453a54e SL |
2879 | /// documentation for more. |
2880 | /// | |
3dfed10e | 2881 | /// [`drain`]: String::drain |
92a42be0 | 2882 | #[stable(feature = "drain", since = "1.6.0")] |
d9579d0f AL |
2883 | pub struct Drain<'a> { |
2884 | /// Will be used as &'a mut String in the destructor | |
2885 | string: *mut String, | |
2886 | /// Start of part to remove | |
2887 | start: usize, | |
2888 | /// End of part to remove | |
2889 | end: usize, | |
2890 | /// Current remaining range to remove | |
2891 | iter: Chars<'a>, | |
2892 | } | |
2893 | ||
8bb4bdeb | 2894 | #[stable(feature = "collection_debug", since = "1.17.0")] |
9fa01778 XL |
2895 | impl fmt::Debug for Drain<'_> { |
2896 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
1b1a35ee | 2897 | f.debug_tuple("Drain").field(&self.as_str()).finish() |
8bb4bdeb XL |
2898 | } |
2899 | } | |
2900 | ||
92a42be0 | 2901 | #[stable(feature = "drain", since = "1.6.0")] |
9fa01778 | 2902 | unsafe impl Sync for Drain<'_> {} |
92a42be0 | 2903 | #[stable(feature = "drain", since = "1.6.0")] |
9fa01778 | 2904 | unsafe impl Send for Drain<'_> {} |
d9579d0f | 2905 | |
92a42be0 | 2906 | #[stable(feature = "drain", since = "1.6.0")] |
9fa01778 | 2907 | impl Drop for Drain<'_> { |
d9579d0f AL |
2908 | fn drop(&mut self) { |
2909 | unsafe { | |
2910 | // Use Vec::drain. "Reaffirm" the bounds checks to avoid | |
2911 | // panic code being inserted again. | |
2912 | let self_vec = (*self.string).as_mut_vec(); | |
2913 | if self.start <= self.end && self.end <= self_vec.len() { | |
2914 | self_vec.drain(self.start..self.end); | |
2915 | } | |
2916 | } | |
2917 | } | |
2918 | } | |
2919 | ||
1b1a35ee XL |
2920 | impl<'a> Drain<'a> { |
2921 | /// Returns the remaining (sub)string of this iterator as a slice. | |
2922 | /// | |
2923 | /// # Examples | |
2924 | /// | |
2925 | /// ``` | |
1b1a35ee XL |
2926 | /// let mut s = String::from("abc"); |
2927 | /// let mut drain = s.drain(..); | |
2928 | /// assert_eq!(drain.as_str(), "abc"); | |
2929 | /// let _ = drain.next().unwrap(); | |
2930 | /// assert_eq!(drain.as_str(), "bc"); | |
2931 | /// ``` | |
c295e0f8 | 2932 | #[must_use] |
136023e0 | 2933 | #[stable(feature = "string_drain_as_str", since = "1.55.0")] |
1b1a35ee XL |
2934 | pub fn as_str(&self) -> &str { |
2935 | self.iter.as_str() | |
2936 | } | |
2937 | } | |
2938 | ||
136023e0 XL |
2939 | #[stable(feature = "string_drain_as_str", since = "1.55.0")] |
2940 | impl<'a> AsRef<str> for Drain<'a> { | |
2941 | fn as_ref(&self) -> &str { | |
2942 | self.as_str() | |
2943 | } | |
2944 | } | |
2945 | ||
2946 | #[stable(feature = "string_drain_as_str", since = "1.55.0")] | |
2947 | impl<'a> AsRef<[u8]> for Drain<'a> { | |
2948 | fn as_ref(&self) -> &[u8] { | |
2949 | self.as_str().as_bytes() | |
2950 | } | |
2951 | } | |
1b1a35ee | 2952 | |
92a42be0 | 2953 | #[stable(feature = "drain", since = "1.6.0")] |
9fa01778 | 2954 | impl Iterator for Drain<'_> { |
d9579d0f AL |
2955 | type Item = char; |
2956 | ||
2957 | #[inline] | |
2958 | fn next(&mut self) -> Option<char> { | |
2959 | self.iter.next() | |
2960 | } | |
2961 | ||
2962 | fn size_hint(&self) -> (usize, Option<usize>) { | |
2963 | self.iter.size_hint() | |
2964 | } | |
416331ca XL |
2965 | |
2966 | #[inline] | |
2967 | fn last(mut self) -> Option<char> { | |
2968 | self.next_back() | |
2969 | } | |
d9579d0f AL |
2970 | } |
2971 | ||
92a42be0 | 2972 | #[stable(feature = "drain", since = "1.6.0")] |
9fa01778 | 2973 | impl DoubleEndedIterator for Drain<'_> { |
d9579d0f AL |
2974 | #[inline] |
2975 | fn next_back(&mut self) -> Option<char> { | |
2976 | self.iter.next_back() | |
2977 | } | |
1a4d82fc | 2978 | } |
9e0c209e | 2979 | |
0531ce1d | 2980 | #[stable(feature = "fused", since = "1.26.0")] |
9fa01778 | 2981 | impl FusedIterator for Drain<'_> {} |
f035d41b | 2982 | |
17df50a5 | 2983 | #[cfg(not(no_global_oom_handling))] |
f035d41b XL |
2984 | #[stable(feature = "from_char_for_string", since = "1.46.0")] |
2985 | impl From<char> for String { | |
17df50a5 XL |
2986 | /// Allocates an owned [`String`] from a single character. |
2987 | /// | |
2988 | /// # Example | |
2989 | /// ```rust | |
2990 | /// let c: char = 'a'; | |
2991 | /// let s: String = String::from(c); | |
2992 | /// assert_eq!("a", &s[..]); | |
2993 | /// ``` | |
f035d41b XL |
2994 | #[inline] |
2995 | fn from(c: char) -> Self { | |
2996 | c.to_string() | |
2997 | } | |
2998 | } |