rune_alloc/string/mod.rs
1//! A UTF-8βencoded, growable string.
2//!
3//! This module contains the [`String`] type, the [`TryToString`] trait for
4//! converting to strings, and several error types that may result from working
5//! with [`String`]s.
6//!
7//! # Examples
8//!
9//! There are multiple ways to create a new [`String`] from a string literal:
10//!
11//! ```
12//! use rune::alloc::prelude::*;
13//!
14//! let s = "Hello".try_to_string()?;
15//!
16//! let s = String::try_from("world")?;
17//! let s: String = "also this".try_into()?;
18//! # Ok::<_, rune::alloc::Error>(())
19//! ```
20//!
21//! If you have a vector of valid UTF-8 bytes, you can make a [`String`] out of
22//! it. You can do the reverse too.
23//!
24//! ```
25//! use rune::alloc::prelude::*;
26//!
27//! let sparkle_heart = try_vec![240, 159, 146, 150];
28//! let sparkle_heart = String::from_utf8(sparkle_heart)?;
29//!
30//! assert_eq!("π", sparkle_heart);
31//!
32//! let bytes = sparkle_heart.into_bytes();
33//!
34//! assert_eq!(bytes, [240, 159, 146, 150]);
35//! # Ok::<_, std::boxed::Box<dyn core::error::Error>>(())
36//! ```
37
38#[cfg(feature = "serde")]
39mod serde;
40
41pub use self::try_to_string::TryToString;
42pub(crate) mod try_to_string;
43
44#[cfg(feature = "alloc")]
45use core::alloc::Layout;
46use core::borrow::Borrow;
47use core::cmp::Ordering;
48use core::fmt;
49use core::hash;
50use core::iter::FusedIterator;
51#[cfg(feature = "alloc")]
52use core::mem::ManuallyDrop;
53use core::ops::Bound::{Excluded, Included, Unbounded};
54use core::ops::{self, Index, IndexMut, Range, RangeBounds};
55use core::ptr;
56use core::slice;
57use core::str::{from_utf8, from_utf8_unchecked, from_utf8_unchecked_mut};
58use core::str::{Chars, Utf8Error};
59
60use crate::alloc::{Allocator, Global};
61use crate::borrow::Cow;
62use crate::boxed::Box;
63use crate::clone::TryClone;
64use crate::error::Error;
65use crate::fmt::TryWrite;
66use crate::iter::{TryExtend, TryFromIteratorIn, TryJoin};
67use crate::slice::range as slice_range;
68#[cfg(test)]
69use crate::testing::*;
70use crate::vec::Vec;
71
72/// A UTF-8βencoded, growable string.
73///
74/// The `String` type is the most common string type that has ownership over the
75/// contents of the string. It has a close relationship with its borrowed
76/// counterpart, the primitive [`str`].
77///
78/// # Examples
79///
80/// You can create a `String` from [a literal string][`&str`] with
81/// [`String::try_from`]:
82///
83/// [`String::try_from`]: TryFrom::try_from
84///
85/// ```
86/// use rune::alloc::String;
87///
88/// let hello = String::try_from("Hello, world!")?;
89/// # Ok::<_, rune::alloc::Error>(())
90/// ```
91///
92/// You can append a [`char`] to a `String` with the [`try_push`] method, and
93/// append a [`&str`] with the [`try_push_str`] method:
94///
95/// ```
96/// use rune::alloc::String;
97///
98/// let mut hello = String::try_from("Hello, ")?;
99///
100/// hello.try_push('w')?;
101/// hello.try_push_str("orld!")?;
102/// # Ok::<_, rune::alloc::Error>(())
103/// ```
104///
105/// [`try_push`]: String::try_push
106/// [`try_push_str`]: String::try_push_str
107///
108/// If you have a vector of UTF-8 bytes, you can create a `String` from it with
109/// the [`from_utf8`] method:
110///
111/// ```
112/// use rune::alloc::{try_vec, String};
113///
114/// // some bytes, in a vector
115/// let sparkle_heart = try_vec![240, 159, 146, 150];
116/// let sparkle_heart = String::from_utf8(sparkle_heart)?;
117///
118/// assert_eq!("π", sparkle_heart);
119/// # Ok::<_, Box<dyn core::error::Error>>(())
120/// ```
121///
122/// [`from_utf8`]: String::from_utf8
123///
124/// # UTF-8
125///
126/// `String`s are always valid UTF-8. If you need a non-UTF-8 string, consider
127/// [`OsString`]. It is similar, but without the UTF-8 constraint. Because UTF-8
128/// is a variable width encoding, `String`s are typically smaller than an array of
129/// the same `chars`:
130///
131/// ```
132/// use core::mem;
133///
134/// // `s` is ASCII which represents each `char` as one byte
135/// let s = "hello";
136/// assert_eq!(s.len(), 5);
137///
138/// // A `char` array with the same contents would be longer because
139/// // every `char` is four bytes
140/// let s = ['h', 'e', 'l', 'l', 'o'];
141/// let size: usize = s.into_iter().map(|c| mem::size_of_val(&c)).sum();
142/// assert_eq!(size, 20);
143///
144/// // However, for non-ASCII strings, the difference will be smaller
145/// // and sometimes they are the same
146/// let s = "πππππ";
147/// assert_eq!(s.len(), 20);
148///
149/// let s = ['π', 'π', 'π', 'π', 'π'];
150/// let size: usize = s.into_iter().map(|c| mem::size_of_val(&c)).sum();
151/// assert_eq!(size, 20);
152/// ```
153///
154/// This raises interesting questions as to how `s[i]` should work.
155/// What should `i` be here? Several options include byte indices and
156/// `char` indices but, because of UTF-8 encoding, only byte indices
157/// would provide constant time indexing. Getting the `i`th `char`, for
158/// example, is available using [`chars`]:
159///
160/// ```
161/// let s = "hello";
162/// let third_character = s.chars().nth(2);
163/// assert_eq!(third_character, Some('l'));
164///
165/// let s = "πππππ";
166/// let third_character = s.chars().nth(2);
167/// assert_eq!(third_character, Some('π'));
168/// ```
169///
170/// Next, what should `s[i]` return? Because indexing returns a reference
171/// to underlying data it could be `&u8`, `&[u8]`, or something else similar.
172/// Since we're only providing one index, `&u8` makes the most sense but that
173/// might not be what the user expects and can be explicitly achieved with
174/// [`as_bytes()`]:
175///
176/// ```
177/// // The first byte is 104 - the byte value of `'h'`
178/// let s = "hello";
179/// assert_eq!(s.as_bytes()[0], 104);
180/// // or
181/// assert_eq!(s.as_bytes()[0], b'h');
182///
183/// // The first byte is 240 which isn't obviously useful
184/// let s = "πππππ";
185/// assert_eq!(s.as_bytes()[0], 240);
186/// ```
187///
188/// Due to these ambiguities/restrictions, indexing with a `usize` is simply
189/// forbidden:
190///
191/// ```compile_fail,E0277
192/// let s = "hello";
193///
194/// // The following will not compile!
195/// println!("The first letter of s is {}", s[0]);
196/// ```
197///
198/// It is more clear, however, how `&s[i..j]` should work (that is,
199/// indexing with a range). It should accept byte indices (to be constant-time)
200/// and return a `&str` which is UTF-8 encoded. This is also called "string slicing".
201/// Note this will panic if the byte indices provided are not character
202/// boundaries - see [`is_char_boundary`] for more details. See the implementations
203/// for [`SliceIndex<str>`] for more details on string slicing. For a non-panicking
204/// version of string slicing, see [`get`].
205///
206/// [`OsString`]: ../../std/ffi/struct.OsString.html "ffi::OsString"
207/// [`SliceIndex<str>`]: core::slice::SliceIndex
208/// [`as_bytes()`]: str::as_bytes
209/// [`get`]: str::get
210/// [`is_char_boundary`]: str::is_char_boundary
211///
212/// The [`bytes`] and [`chars`] methods return iterators over the bytes and
213/// codepoints of the string, respectively. To iterate over codepoints along
214/// with byte indices, use [`char_indices`].
215///
216/// [`bytes`]: str::bytes
217/// [`chars`]: str::chars
218/// [`char_indices`]: str::char_indices
219///
220/// # Deref
221///
222/// `String` implements <code>[Deref]<Target = [str]></code>, and so inherits all of [`str`]'s
223/// methods. In addition, this means that you can pass a `String` to a
224/// function which takes a [`&str`] by using an ampersand (`&`):
225///
226/// ```
227/// use rune::alloc::String;
228///
229/// fn takes_str(s: &str) { }
230///
231/// let s = String::try_from("Hello")?;
232///
233/// takes_str(&s);
234/// # Ok::<_, rune::alloc::Error>(())
235/// ```
236///
237/// This will create a [`&str`] from the `String` and pass it in. This
238/// conversion is very inexpensive, and so generally, functions will accept
239/// [`&str`]s as arguments unless they need a `String` for some specific
240/// reason.
241///
242/// In certain cases Rust doesn't have enough information to make this
243/// conversion, known as [`Deref`] coercion. In the following example a string
244/// slice [`&'a str`][`&str`] implements the trait `TraitExample`, and the function
245/// `example_func` takes anything that implements the trait. In this case Rust
246/// would need to make two implicit conversions, which Rust doesn't have the
247/// means to do. For that reason, the following example will not compile.
248///
249/// ```compile_fail,E0277
250/// use rune::alloc::String;
251///
252/// trait TraitExample {}
253///
254/// impl<'a> TraitExample for &'a str {}
255///
256/// fn example_func<A>(example_arg: A) where A: TraitExample {}
257///
258/// let example_string = String::try_from("example_string")?;
259/// example_func(&example_string);
260/// # Ok::<_, rune::alloc::Error>(())
261/// ```
262///
263/// There are two options that would work instead. The first would be to
264/// change the line `example_func(&example_string);` to
265/// `example_func(example_string.as_str());`, using the method [`as_str()`]
266/// to explicitly extract the string slice containing the string. The second
267/// way changes `example_func(&example_string);` to
268/// `example_func(&*example_string);`. In this case we are dereferencing a
269/// `String` to a [`str`], then referencing the [`str`] back to
270/// [`&str`]. The second way is more idiomatic, however both work to do the
271/// conversion explicitly rather than relying on the implicit conversion.
272///
273/// # Representation
274///
275/// A `String` is made up of three components: a pointer to some bytes, a
276/// length, and a capacity. The pointer points to an internal buffer `String`
277/// uses to store its data. The length is the number of bytes currently stored
278/// in the buffer, and the capacity is the size of the buffer in bytes. As such,
279/// the length will always be less than or equal to the capacity.
280///
281/// This buffer is always stored on the heap.
282///
283/// You can look at these with the [`as_ptr`], [`len`], and [`capacity`]
284/// methods:
285///
286/// ```
287/// use core::mem;
288/// use rune::alloc::String;
289///
290/// let story = String::try_from("Once upon a time...")?;
291///
292/// // Prevent automatically dropping the String's data
293/// let mut story = mem::ManuallyDrop::new(story);
294///
295/// let ptr = story.as_mut_ptr();
296/// let len = story.len();
297/// let capacity = story.capacity();
298/// let allocator = story.allocator().clone();
299///
300/// // story has nineteen bytes
301/// assert_eq!(19, len);
302///
303/// // We can re-build a String out of ptr, len, and capacity. This is all
304/// // unsafe because we are responsible for making sure the components are
305/// // valid:
306/// let s = unsafe { String::from_raw_parts_in(ptr, len, capacity, allocator) } ;
307///
308/// assert_eq!("Once upon a time...", s);
309/// # Ok::<_, rune::alloc::Error>(())
310/// ```
311///
312/// [`as_ptr`]: str::as_ptr
313/// [`len`]: String::len
314/// [`capacity`]: String::capacity
315///
316/// If a `String` has enough capacity, adding elements to it will not
317/// re-allocate. For example, consider this program:
318///
319/// ```
320/// use rune::alloc::String;
321///
322/// let mut s = String::new();
323///
324/// println!("{}", s.capacity());
325///
326/// for _ in 0..5 {
327/// s.try_push_str("hello")?;
328/// println!("{}", s.capacity());
329/// }
330/// # Ok::<_, rune::alloc::Error>(())
331/// ```
332///
333/// This will output the following:
334///
335/// ```text
336/// 0
337/// 8
338/// 16
339/// 16
340/// 32
341/// 32
342/// ```
343///
344/// At first, we have no memory allocated at all, but as we append to the
345/// string, it increases its capacity appropriately. If we instead use the
346/// [`try_with_capacity_in`] method to allocate the correct capacity initially:
347///
348/// ```
349/// use rune::alloc::String;
350/// use rune::alloc::alloc::Global;
351///
352/// let mut s = String::try_with_capacity_in(25, Global)?;
353///
354/// println!("{}", s.capacity());
355///
356/// for _ in 0..5 {
357/// s.try_push_str("hello")?;
358/// println!("{}", s.capacity());
359/// }
360/// # Ok::<_, rune::alloc::Error>(())
361/// ```
362///
363/// [`try_with_capacity_in`]: String::try_with_capacity_in
364///
365/// We end up with a different output:
366///
367/// ```text
368/// 25
369/// 25
370/// 25
371/// 25
372/// 25
373/// 25
374/// ```
375///
376/// Here, there's no need to allocate more memory inside the loop.
377///
378/// [str]: prim@str "str"
379/// [`str`]: prim@str "str"
380/// [`&str`]: prim@str "&str"
381/// [Deref]: core::ops::Deref "ops::Deref"
382/// [`Deref`]: core::ops::Deref "ops::Deref"
383/// [`as_str()`]: String::as_str
384pub struct String<A: Allocator = Global> {
385 vec: Vec<u8, A>,
386}
387
388impl String {
389 /// Creates a new empty `String`.
390 ///
391 /// Given that the `String` is empty, this will not allocate any initial
392 /// buffer. While that means that this initial operation is very
393 /// inexpensive, it may cause excessive allocation later when you add data.
394 /// If you have an idea of how much data the `String` will hold, consider
395 /// the [`try_with_capacity`] method to prevent excessive re-allocation.
396 ///
397 /// [`try_with_capacity`]: String::try_with_capacity
398 ///
399 /// # Examples
400 ///
401 /// Basic usage:
402 ///
403 /// ```
404 /// use rune::alloc::String;
405 ///
406 /// let s = String::new();
407 /// ```
408 #[inline]
409 #[must_use]
410 pub const fn new() -> Self {
411 String { vec: Vec::new() }
412 }
413
414 /// Creates a new empty `String` with at least the specified capacity.
415 ///
416 /// `String`s have an internal buffer to hold their data. The capacity is
417 /// the length of that buffer, and can be queried with the [`capacity`]
418 /// method. This method creates an empty `String`, but one with an initial
419 /// buffer that can hold at least `capacity` bytes. This is useful when you
420 /// may be appending a bunch of data to the `String`, reducing the number of
421 /// reallocations it needs to do.
422 ///
423 /// [`capacity`]: String::capacity
424 ///
425 /// If the given capacity is `0`, no allocation will occur, and this method
426 /// is identical to the [`new`] method.
427 ///
428 /// [`new`]: String::new
429 ///
430 /// # Examples
431 ///
432 /// Basic usage:
433 ///
434 /// ```
435 /// use rune::alloc::String;
436 ///
437 /// let mut s = String::try_with_capacity(10)?;
438 ///
439 /// // The String contains no chars, even though it has capacity for more
440 /// assert_eq!(s.len(), 0);
441 ///
442 /// // These are all done without reallocating...
443 /// let cap = s.capacity();
444 ///
445 /// for _ in 0..10 {
446 /// s.try_push('a')?;
447 /// }
448 ///
449 /// assert_eq!(s.capacity(), cap);
450 ///
451 /// // ...but this may make the string reallocate
452 /// s.try_push('a')?;
453 /// # Ok::<_, rune::alloc::Error>(())
454 /// ```
455 #[inline]
456 pub fn try_with_capacity(capacity: usize) -> Result<Self, Error> {
457 Ok(String {
458 vec: Vec::try_with_capacity_in(capacity, Global)?,
459 })
460 }
461
462 /// Convert a [`String`] into a std `String`.
463 ///
464 /// The result is allocated on the heap, using the default global allocator
465 /// so this is a zero-copy operation.
466 ///
467 /// The memory previously occupied by this vector will be released.
468 #[cfg(feature = "alloc")]
469 pub fn into_std(self) -> rust_alloc::string::String {
470 // SAFETY: The interior vector is valid UTF-8.
471 unsafe { rust_alloc::string::String::from_utf8_unchecked(self.vec.into_std()) }
472 }
473
474 #[cfg(test)]
475 pub fn from(value: &str) -> Self {
476 Self::try_from(value).abort()
477 }
478}
479
480/// A possible error value when converting a `String` from a UTF-8 byte vector.
481///
482/// This type is the error type for the [`from_utf8`] method on [`String`]. It
483/// is designed in such a way to carefully avoid reallocations: the
484/// [`into_bytes`] method will give back the byte vector that was used in the
485/// conversion attempt.
486///
487/// [`from_utf8`]: String::from_utf8
488/// [`into_bytes`]: FromUtf8Error::into_bytes
489///
490/// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
491/// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
492/// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
493/// through the [`utf8_error`] method.
494///
495/// [`Utf8Error`]: core::str::Utf8Error "std::str::Utf8Error"
496/// [`std::str`]: core::str "std::str"
497/// [`&str`]: prim@str "&str"
498/// [`utf8_error`]: FromUtf8Error::utf8_error
499///
500/// # Examples
501///
502/// ```
503/// use rune::alloc::{try_vec, String};
504///
505/// // some invalid bytes, in a vector
506/// let bytes = try_vec![0, 159];
507///
508/// let value = String::from_utf8(bytes);
509///
510/// assert!(value.is_err());
511/// assert_eq!(try_vec![0, 159], value.unwrap_err().into_bytes());
512/// # Ok::<_, rune::alloc::Error>(())
513/// ```
514pub struct FromUtf8Error<A: Allocator = Global> {
515 bytes: Vec<u8, A>,
516 error: Utf8Error,
517}
518
519impl<A> fmt::Debug for FromUtf8Error<A>
520where
521 A: Allocator,
522{
523 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
524 f.debug_struct("FromUtf8Error")
525 .field("bytes", &self.bytes)
526 .field("error", &self.error)
527 .finish()
528 }
529}
530
531impl<A> PartialEq for FromUtf8Error<A>
532where
533 A: Allocator,
534{
535 fn eq(&self, other: &Self) -> bool {
536 self.bytes == other.bytes && self.error == other.error
537 }
538}
539
540impl<A> Eq for FromUtf8Error<A> where A: Allocator {}
541
542impl<A> String<A>
543where
544 A: Allocator,
545{
546 /// Creates a new empty `String`.
547 ///
548 /// Given that the `String` is empty, this will not allocate any initial
549 /// buffer. While that means that this initial operation is very
550 /// inexpensive, it may cause excessive allocation later when you add data.
551 /// If you have an idea of how much data the `String` will hold, consider
552 /// the [`try_with_capacity_in`] method to prevent excessive re-allocation.
553 ///
554 /// [`try_with_capacity_in`]: String::try_with_capacity_in
555 ///
556 /// # Examples
557 ///
558 /// ```
559 /// use rune::alloc::String;
560 /// use rune::alloc::alloc::Global;
561 ///
562 /// let s = String::new_in(Global);
563 /// ```
564 #[inline]
565 #[must_use]
566 pub fn new_in(alloc: A) -> String<A> {
567 String {
568 vec: Vec::new_in(alloc),
569 }
570 }
571
572 /// Returns a reference to the underlying allocator.
573 ///
574 /// # Examples
575 ///
576 /// ```
577 /// use rune::alloc::String;
578 /// use rune::alloc::alloc::Global;
579 ///
580 /// let s = String::new_in(Global);
581 /// let alloc: &Global = s.allocator();
582 /// ```
583 #[inline]
584 pub fn allocator(&self) -> &A {
585 self.vec.allocator()
586 }
587
588 /// Creates a new empty `String` with at least the specified capacity.
589 ///
590 /// `String`s have an internal buffer to hold their data. The capacity is
591 /// the length of that buffer, and can be queried with the [`capacity`]
592 /// method. This method creates an empty `String`, but one with an initial
593 /// buffer that can hold at least `capacity` bytes. This is useful when you
594 /// may be appending a bunch of data to the `String`, reducing the number of
595 /// reallocations it needs to do.
596 ///
597 /// [`capacity`]: String::capacity
598 ///
599 /// If the given capacity is `0`, no allocation will occur, and this method
600 /// is identical to the [`new_in`] method.
601 ///
602 /// [`new_in`]: String::new_in
603 ///
604 /// # Examples
605 ///
606 /// ```
607 /// use rune::alloc::String;
608 /// use rune::alloc::alloc::Global;
609 ///
610 /// let mut s = String::try_with_capacity_in(10, Global)?;
611 ///
612 /// // The String contains no chars, even though it has capacity for more
613 /// assert_eq!(s.len(), 0);
614 ///
615 /// // These are all done without reallocating...
616 /// let cap = s.capacity();
617 ///
618 /// for _ in 0..10 {
619 /// s.try_push('a')?;
620 /// }
621 ///
622 /// assert_eq!(s.capacity(), cap);
623 ///
624 /// // ...but this may make the string reallocate
625 /// s.try_push('a')?;
626 /// # Ok::<_, rune::alloc::Error>(())
627 /// ```
628 #[inline]
629 pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result<String<A>, Error> {
630 Ok(String {
631 vec: Vec::try_with_capacity_in(capacity, alloc)?,
632 })
633 }
634
635 /// Converts a vector of bytes to a `String`.
636 ///
637 /// A string ([`String`]) is made of bytes ([`u8`]), and a vector of bytes
638 /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
639 /// two. Not all byte slices are valid `String`s, however: `String` requires
640 /// that it is valid UTF-8. `from_utf8()` checks to ensure that the bytes
641 /// are valid UTF-8, and then does the conversion.
642 ///
643 /// If you are sure that the byte slice is valid UTF-8, and you don't want
644 /// to incur the overhead of the validity check, there is an unsafe version
645 /// of this function, [`from_utf8_unchecked`], which has the same behavior
646 /// but skips the check.
647 ///
648 /// This method will take care to not copy the vector, for efficiency's
649 /// sake.
650 ///
651 /// If you need a [`&str`] instead of a `String`, consider
652 /// [`str::from_utf8`].
653 ///
654 /// The inverse of this method is [`into_bytes`].
655 ///
656 /// [`str::from_utf8`]: core::str::from_utf8
657 ///
658 /// # Errors
659 ///
660 /// Returns [`Err`] if the slice is not UTF-8 with a description as to why
661 /// the provided bytes are not UTF-8. The vector you moved in is also
662 /// included.
663 ///
664 /// # Examples
665 ///
666 /// Basic usage:
667 ///
668 /// ```
669 /// use rune::alloc::{try_vec, String};
670 ///
671 /// // some bytes, in a vector
672 /// let sparkle_heart = try_vec![240, 159, 146, 150];
673 /// let sparkle_heart = String::from_utf8(sparkle_heart)?;
674 ///
675 /// assert_eq!("π", sparkle_heart);
676 /// # Ok::<_, Box<dyn core::error::Error>>(())
677 /// ```
678 ///
679 /// Incorrect bytes:
680 ///
681 /// ```
682 /// use rune::alloc::{try_vec, String};
683 ///
684 /// // some invalid bytes, in a vector
685 /// let sparkle_heart = try_vec![0, 159, 146, 150];
686 ///
687 /// assert!(String::from_utf8(sparkle_heart).is_err());
688 /// # Ok::<_, rune::alloc::Error>(())
689 /// ```
690 ///
691 /// See the docs for [`FromUtf8Error`] for more details on what you can do
692 /// with this error.
693 ///
694 /// [`from_utf8_unchecked`]: String::from_utf8_unchecked
695 /// [`Vec<u8>`]: crate::vec::Vec "Vec"
696 /// [`&str`]: prim@str "&str"
697 /// [`into_bytes`]: String::into_bytes
698 #[inline]
699 pub fn from_utf8(vec: Vec<u8, A>) -> Result<String<A>, FromUtf8Error<A>> {
700 match from_utf8(&vec) {
701 Ok(..) => Ok(String { vec }),
702 Err(e) => Err(FromUtf8Error {
703 bytes: vec,
704 error: e,
705 }),
706 }
707 }
708
709 /// Creates a new `String` from a length, capacity, and pointer.
710 ///
711 /// # Safety
712 ///
713 /// This is highly unsafe, due to the number of invariants that aren't
714 /// checked:
715 ///
716 /// * The memory at `buf` needs to have been previously allocated by the
717 /// same allocator the standard library uses, with a required alignment of exactly 1.
718 /// * `length` needs to be less than or equal to `capacity`.
719 /// * `capacity` needs to be the correct value.
720 /// * The first `length` bytes at `buf` need to be valid UTF-8.
721 ///
722 /// Violating these may cause problems like corrupting the allocator's
723 /// internal data structures. For example, it is normally **not** safe to
724 /// build a `String` from a pointer to a C `char` array containing UTF-8
725 /// _unless_ you are certain that array was originally allocated by the
726 /// Rust standard library's allocator.
727 ///
728 /// The ownership of `buf` is effectively transferred to the
729 /// `String` which may then deallocate, reallocate or change the
730 /// contents of memory pointed to by the pointer at will. Ensure
731 /// that nothing else uses the pointer after calling this
732 /// function.
733 ///
734 /// # Examples
735 ///
736 /// ```
737 /// use rune::alloc::String;
738 /// use core::mem;
739 ///
740 /// unsafe {
741 /// let s = String::try_from("hello")?;
742 ///
743 /// // Prevent automatically dropping the String's data
744 /// let mut s = mem::ManuallyDrop::new(s);
745 ///
746 /// let ptr = s.as_mut_ptr();
747 /// let len = s.len();
748 /// let capacity = s.capacity();
749 /// let allocator = s.allocator().clone();
750 ///
751 /// let s = String::from_raw_parts_in(ptr, len, capacity, allocator);
752 ///
753 /// assert_eq!("hello", s);
754 /// }
755 /// # Ok::<_, rune::alloc::Error>(())
756 /// ```
757 #[inline]
758 pub unsafe fn from_raw_parts_in(
759 buf: *mut u8,
760 length: usize,
761 capacity: usize,
762 alloc: A,
763 ) -> String<A> {
764 unsafe {
765 String {
766 vec: Vec::from_raw_parts_in(buf, length, capacity, alloc),
767 }
768 }
769 }
770
771 /// Converts a vector of bytes to a `String` without checking that the
772 /// string contains valid UTF-8.
773 ///
774 /// See the safe version, [`from_utf8`], for more details.
775 ///
776 /// [`from_utf8`]: String::from_utf8
777 ///
778 /// # Safety
779 ///
780 /// This function is unsafe because it does not check that the bytes passed
781 /// to it are valid UTF-8. If this constraint is violated, it may cause
782 /// memory unsafety issues with future users of the `String`, as the rest of
783 /// the standard library assumes that `String`s are valid UTF-8.
784 ///
785 /// # Examples
786 ///
787 /// ```
788 /// use rune::alloc::{try_vec, String};
789 ///
790 /// // some bytes, in a vector
791 /// let sparkle_heart = try_vec![240, 159, 146, 150];
792 ///
793 /// let sparkle_heart = unsafe {
794 /// String::from_utf8_unchecked(sparkle_heart)
795 /// };
796 ///
797 /// assert_eq!("π", sparkle_heart);
798 /// # Ok::<_, rune::alloc::Error>(())
799 /// ```
800 #[inline]
801 #[must_use]
802 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8, A>) -> String<A> {
803 String { vec: bytes }
804 }
805
806 /// Converts a `String` into a byte vector.
807 ///
808 /// This consumes the `String`, so we do not need to copy its contents.
809 ///
810 /// # Examples
811 ///
812 /// ```
813 /// use rune::alloc::String;
814 ///
815 /// let s = String::try_from("hello")?;
816 /// let bytes = s.into_bytes();
817 ///
818 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
819 /// # Ok::<_, rune::alloc::Error>(())
820 /// ```
821 #[inline]
822 #[must_use = "`self` will be dropped if the result is not used"]
823 pub fn into_bytes(self) -> Vec<u8, A> {
824 self.vec
825 }
826
827 /// Extracts a string slice containing the entire `String`.
828 ///
829 /// # Examples
830 ///
831 /// ```
832 /// use rune::alloc::String;
833 ///
834 /// let s = String::try_from("foo")?;
835 ///
836 /// assert_eq!("foo", s.as_str());
837 /// # Ok::<_, rune::alloc::Error>(())
838 /// ```
839 #[inline]
840 #[must_use]
841 pub fn as_str(&self) -> &str {
842 self
843 }
844
845 /// Converts a `String` into a mutable string slice.
846 ///
847 /// # Examples
848 ///
849 /// ```
850 /// use rune::alloc::String;
851 ///
852 /// let mut s = String::try_from("foobar")?;
853 /// let s_mut_str = s.as_mut_str();
854 ///
855 /// s_mut_str.make_ascii_uppercase();
856 ///
857 /// assert_eq!("FOOBAR", s_mut_str);
858 /// # Ok::<_, rune::alloc::Error>(())
859 /// ```
860 #[inline]
861 #[must_use]
862 pub fn as_mut_str(&mut self) -> &mut str {
863 self
864 }
865
866 /// Appends a given string slice onto the end of this `String`.
867 ///
868 /// # Examples
869 ///
870 /// ```
871 /// use rune::alloc::String;
872 /// use rune::alloc::alloc::Global;
873 ///
874 /// let mut s = String::try_with_capacity_in(3, Global)?;
875 ///
876 /// s.try_push_str("foo")?;
877 /// s.try_push_str("bar")?;
878 ///
879 /// assert_eq!("foobar", s);
880 /// # Ok::<_, rune::alloc::Error>(())
881 /// ```
882 #[inline]
883 pub fn try_push_str(&mut self, string: &str) -> Result<(), Error> {
884 self.vec.try_extend_from_slice(string.as_bytes())
885 }
886
887 #[cfg(test)]
888 pub(crate) fn push_str(&mut self, string: &str) {
889 self.try_push_str(string).abort()
890 }
891
892 /// Returns this `String`'s capacity, in bytes.
893 ///
894 /// # Examples
895 ///
896 /// ```
897 /// use rune::alloc::String;
898 /// use rune::alloc::alloc::Global;
899 ///
900 /// let s = String::try_with_capacity_in(10, Global)?;
901 ///
902 /// assert!(s.capacity() >= 10);
903 /// # Ok::<_, rune::alloc::Error>(())
904 /// ```
905 #[inline]
906 #[must_use]
907 pub fn capacity(&self) -> usize {
908 self.vec.capacity()
909 }
910
911 /// Tries to reserve capacity for at least `additional` bytes more than the
912 /// current length. The allocator may reserve more space to speculatively
913 /// avoid frequent allocations. After calling `try_reserve`, capacity will be
914 /// greater than or equal to `self.len() + additional` if it returns
915 /// `Ok(())`. Does nothing if capacity is already sufficient. This method
916 /// preserves the contents even if an error occurs.
917 ///
918 /// # Errors
919 ///
920 /// If the capacity overflows, or the allocator reports a failure, then an error
921 /// is returned.
922 ///
923 /// # Examples
924 ///
925 /// ```
926 /// use rune::alloc::{String, Error};
927 ///
928 /// fn process_data(data: &str) -> Result<String, Error> {
929 /// let mut output = String::new();
930 ///
931 /// // Pre-reserve the memory, exiting if we can't
932 /// output.try_reserve(data.len())?;
933 ///
934 /// // Now we know this can't OOM in the middle of our complex work
935 /// output.try_push_str(data)?;
936 ///
937 /// Ok(output)
938 /// }
939 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
940 /// ```
941 pub fn try_reserve(&mut self, additional: usize) -> Result<(), Error> {
942 self.vec.try_reserve(additional)
943 }
944
945 /// Tries to reserve the minimum capacity for at least `additional` bytes
946 /// more than the current length. Unlike [`try_reserve`], this will not
947 /// deliberately over-allocate to speculatively avoid frequent allocations.
948 /// After calling `try_reserve_exact`, capacity will be greater than or
949 /// equal to `self.len() + additional` if it returns `Ok(())`.
950 /// Does nothing if the capacity is already sufficient.
951 ///
952 /// Note that the allocator may give the collection more space than it
953 /// requests. Therefore, capacity can not be relied upon to be precisely
954 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
955 ///
956 /// [`try_reserve`]: String::try_reserve
957 ///
958 /// # Errors
959 ///
960 /// If the capacity overflows, or the allocator reports a failure, then an error
961 /// is returned.
962 ///
963 /// # Examples
964 ///
965 /// ```
966 /// use rune::alloc::{String, Error};
967 ///
968 /// fn process_data(data: &str) -> Result<String, Error> {
969 /// let mut output = String::new();
970 ///
971 /// // Pre-reserve the memory, exiting if we can't
972 /// output.try_reserve_exact(data.len())?;
973 ///
974 /// // Now we know this can't OOM in the middle of our complex work
975 /// output.try_push_str(data);
976 ///
977 /// Ok(output)
978 /// }
979 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
980 /// ```
981 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), Error> {
982 self.vec.try_reserve_exact(additional)
983 }
984
985 /// Shrinks the capacity of this `String` to match its length.
986 ///
987 /// # Examples
988 ///
989 /// ```
990 /// use rune::alloc::String;
991 /// let mut s = String::try_from("foo")?;
992 ///
993 /// s.try_reserve(100)?;
994 /// assert!(s.capacity() >= 100);
995 ///
996 /// s.try_shrink_to_fit()?;
997 /// assert_eq!(3, s.capacity());
998 /// # Ok::<_, rune::alloc::Error>(())
999 /// ```
1000 #[inline]
1001 pub fn try_shrink_to_fit(&mut self) -> Result<(), Error> {
1002 self.vec.try_shrink_to_fit()
1003 }
1004
1005 /// Shrinks the capacity of this `String` with a lower bound.
1006 ///
1007 /// The capacity will remain at least as large as both the length
1008 /// and the supplied value.
1009 ///
1010 /// If the current capacity is less than the lower limit, this is a no-op.
1011 ///
1012 /// # Examples
1013 ///
1014 /// ```
1015 /// use rune::alloc::String;
1016 ///
1017 /// let mut s = String::try_from("foo")?;
1018 ///
1019 /// s.try_reserve(100)?;
1020 /// assert!(s.capacity() >= 100);
1021 ///
1022 /// s.try_shrink_to(10)?;
1023 /// assert!(s.capacity() >= 10);
1024 /// s.try_shrink_to(0)?;
1025 /// assert!(s.capacity() >= 3);
1026 /// # Ok::<_, rune::alloc::Error>(())
1027 /// ```
1028 #[inline]
1029 pub fn try_shrink_to(&mut self, min_capacity: usize) -> Result<(), Error> {
1030 self.vec.try_shrink_to(min_capacity)
1031 }
1032
1033 /// Appends the given [`char`] to the end of this `String`.
1034 ///
1035 /// # Examples
1036 ///
1037 /// ```
1038 /// use rune::alloc::String;
1039 /// use rune::alloc::alloc::Global;
1040 ///
1041 /// let mut s = String::try_with_capacity_in(3, Global)?;
1042 /// s.try_push_str("abc")?;
1043 ///
1044 /// s.try_push('1')?;
1045 /// s.try_push('2')?;
1046 /// s.try_push('3')?;
1047 ///
1048 /// assert_eq!("abc123", s);
1049 /// # Ok::<_, rune::alloc::Error>(())
1050 /// ```
1051 #[inline]
1052 pub fn try_push(&mut self, ch: char) -> Result<(), Error> {
1053 match ch.len_utf8() {
1054 1 => self.vec.try_push(ch as u8),
1055 _ => self
1056 .vec
1057 .try_extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
1058 }
1059 }
1060
1061 /// Returns a byte slice of this `String`'s contents.
1062 ///
1063 /// The inverse of this method is [`from_utf8`].
1064 ///
1065 /// [`from_utf8`]: String::from_utf8
1066 ///
1067 /// # Examples
1068 ///
1069 /// ```
1070 /// use rune::alloc::String;
1071 ///
1072 /// let s = String::try_from("hello")?;
1073 ///
1074 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
1075 /// # Ok::<_, rune::alloc::Error>(())
1076 /// ```
1077 #[inline]
1078 #[must_use]
1079 pub fn as_bytes(&self) -> &[u8] {
1080 &self.vec
1081 }
1082
1083 /// Shortens this `String` to the specified length.
1084 ///
1085 /// If `new_len` is greater than the string's current length, this has no
1086 /// effect.
1087 ///
1088 /// Note that this method has no effect on the allocated capacity
1089 /// of the string
1090 ///
1091 /// # Panics
1092 ///
1093 /// Panics if `new_len` does not lie on a [`char`] boundary.
1094 ///
1095 /// # Examples
1096 ///
1097 /// ```
1098 /// use rune::alloc::String;
1099 ///
1100 /// let mut s = String::try_from("hello")?;
1101 ///
1102 /// s.truncate(2);
1103 ///
1104 /// assert_eq!("he", s);
1105 /// # Ok::<_, rune::alloc::Error>(())
1106 /// ```
1107 #[inline]
1108 pub fn truncate(&mut self, new_len: usize) {
1109 if new_len <= self.len() {
1110 assert!(self.is_char_boundary(new_len));
1111 self.vec.truncate(new_len)
1112 }
1113 }
1114
1115 /// Removes the last character from the string buffer and returns it.
1116 ///
1117 /// Returns [`None`] if this `String` is empty.
1118 ///
1119 /// # Examples
1120 ///
1121 /// ```
1122 /// use rune::alloc::String;
1123 ///
1124 /// let mut s = String::try_from("abΔ")?;
1125 ///
1126 /// assert_eq!(s.pop(), Some('Δ'));
1127 /// assert_eq!(s.pop(), Some('b'));
1128 /// assert_eq!(s.pop(), Some('a'));
1129 ///
1130 /// assert_eq!(s.pop(), None);
1131 /// # Ok::<_, rune::alloc::Error>(())
1132 /// ```
1133 #[inline]
1134 pub fn pop(&mut self) -> Option<char> {
1135 let ch = self.chars().next_back()?;
1136 let newlen = self.len() - ch.len_utf8();
1137 unsafe {
1138 self.vec.set_len(newlen);
1139 }
1140 Some(ch)
1141 }
1142
1143 /// Removes a [`char`] from this `String` at a byte position and returns it.
1144 ///
1145 /// This is an *O*(*n*) operation, as it requires copying every element in the
1146 /// buffer.
1147 ///
1148 /// # Panics
1149 ///
1150 /// Panics if `idx` is larger than or equal to the `String`'s length,
1151 /// or if it does not lie on a [`char`] boundary.
1152 ///
1153 /// # Examples
1154 ///
1155 /// ```
1156 /// use rune::alloc::String;
1157 ///
1158 /// let mut s = String::try_from("abΓ§")?;
1159 ///
1160 /// assert_eq!(s.remove(0), 'a');
1161 /// assert_eq!(s.remove(1), 'Γ§');
1162 /// assert_eq!(s.remove(0), 'b');
1163 /// # Ok::<_, rune::alloc::Error>(())
1164 /// ```
1165 #[inline]
1166 pub fn remove(&mut self, idx: usize) -> char {
1167 let ch = match self[idx..].chars().next() {
1168 Some(ch) => ch,
1169 None => panic!("cannot remove a char from the end of a string"),
1170 };
1171
1172 let next = idx + ch.len_utf8();
1173 let len = self.len();
1174 unsafe {
1175 ptr::copy(
1176 self.vec.as_ptr().add(next),
1177 self.vec.as_mut_ptr().add(idx),
1178 len - next,
1179 );
1180 self.vec.set_len(len - (next - idx));
1181 }
1182 ch
1183 }
1184
1185 /// Retains only the characters specified by the predicate.
1186 ///
1187 /// In other words, remove all characters `c` such that `f(c)` returns `false`.
1188 /// This method operates in place, visiting each character exactly once in the
1189 /// original order, and preserves the order of the retained characters.
1190 ///
1191 /// # Examples
1192 ///
1193 /// ```
1194 /// use rune::alloc::String;
1195 ///
1196 /// let mut s = String::try_from("f_o_ob_ar")?;
1197 ///
1198 /// s.retain(|c| c != '_');
1199 ///
1200 /// assert_eq!(s, "foobar");
1201 /// # Ok::<_, rune::alloc::Error>(())
1202 /// ```
1203 ///
1204 /// Because the elements are visited exactly once in the original order,
1205 /// external state may be used to decide which elements to keep.
1206 ///
1207 /// ```
1208 /// use rune::alloc::String;
1209 ///
1210 /// let mut s = String::try_from("abcde")?;
1211 /// let keep = [false, true, true, false, true];
1212 /// let mut iter = keep.iter();
1213 /// s.retain(|_| *iter.next().unwrap());
1214 /// assert_eq!(s, "bce");
1215 /// # Ok::<_, rune::alloc::Error>(())
1216 /// ```
1217 #[inline]
1218 pub fn retain<F>(&mut self, mut f: F)
1219 where
1220 F: FnMut(char) -> bool,
1221 {
1222 struct SetLenOnDrop<'a, A>
1223 where
1224 A: Allocator,
1225 {
1226 s: &'a mut String<A>,
1227 idx: usize,
1228 del_bytes: usize,
1229 }
1230
1231 impl<A> Drop for SetLenOnDrop<'_, A>
1232 where
1233 A: Allocator,
1234 {
1235 fn drop(&mut self) {
1236 let new_len = self.idx - self.del_bytes;
1237 debug_assert!(new_len <= self.s.len());
1238 unsafe { self.s.vec.set_len(new_len) };
1239 }
1240 }
1241
1242 let len = self.len();
1243 let mut guard = SetLenOnDrop {
1244 s: self,
1245 idx: 0,
1246 del_bytes: 0,
1247 };
1248
1249 while guard.idx < len {
1250 let ch =
1251 // SAFETY: `guard.idx` is positive-or-zero and less that len so the `get_unchecked`
1252 // is in bound. `self` is valid UTF-8 like string and the returned slice starts at
1253 // a unicode code point so the `Chars` always return one character.
1254 unsafe { guard.s.get_unchecked(guard.idx..len).chars().next().unwrap_unchecked() };
1255 let ch_len = ch.len_utf8();
1256
1257 if !f(ch) {
1258 guard.del_bytes += ch_len;
1259 } else if guard.del_bytes > 0 {
1260 // SAFETY: `guard.idx` is in bound and `guard.del_bytes` represent the number of
1261 // bytes that are erased from the string so the resulting `guard.idx -
1262 // guard.del_bytes` always represent a valid unicode code point.
1263 //
1264 // `guard.del_bytes` >= `ch.len_utf8()`, so taking a slice with `ch.len_utf8()` len
1265 // is safe.
1266 ch.encode_utf8(unsafe {
1267 slice::from_raw_parts_mut(
1268 guard.s.as_mut_ptr().add(guard.idx - guard.del_bytes),
1269 ch.len_utf8(),
1270 )
1271 });
1272 }
1273
1274 // Point idx to the next char
1275 guard.idx += ch_len;
1276 }
1277
1278 drop(guard);
1279 }
1280
1281 /// Inserts a character into this `String` at a byte position.
1282 ///
1283 /// This is an *O*(*n*) operation as it requires copying every element in the
1284 /// buffer.
1285 ///
1286 /// # Panics
1287 ///
1288 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1289 /// lie on a [`char`] boundary.
1290 ///
1291 /// # Examples
1292 ///
1293 /// ```
1294 /// use rune::alloc::String;
1295 /// use rune::alloc::alloc::Global;
1296 ///
1297 /// let mut s = String::try_with_capacity_in(3, Global)?;
1298 ///
1299 /// s.try_insert(0, 'f')?;
1300 /// s.try_insert(1, 'o')?;
1301 /// s.try_insert(2, 'o')?;
1302 ///
1303 /// assert_eq!(s, "foo");
1304 /// # Ok::<_, rune::alloc::Error>(())
1305 /// ```
1306 #[inline]
1307 pub fn try_insert(&mut self, idx: usize, ch: char) -> Result<(), Error> {
1308 assert!(self.is_char_boundary(idx));
1309 let mut bits = [0; 4];
1310 let bits = ch.encode_utf8(&mut bits).as_bytes();
1311
1312 unsafe {
1313 self.insert_bytes(idx, bits)?;
1314 }
1315
1316 Ok(())
1317 }
1318
1319 unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) -> Result<(), Error> {
1320 let len = self.len();
1321 let amt = bytes.len();
1322 self.vec.try_reserve(amt)?;
1323
1324 unsafe {
1325 ptr::copy(
1326 self.vec.as_ptr().add(idx),
1327 self.vec.as_mut_ptr().add(idx + amt),
1328 len - idx,
1329 );
1330 ptr::copy_nonoverlapping(bytes.as_ptr(), self.vec.as_mut_ptr().add(idx), amt);
1331 self.vec.set_len(len + amt);
1332 }
1333
1334 Ok(())
1335 }
1336
1337 /// Inserts a string slice into this `String` at a byte position.
1338 ///
1339 /// This is an *O*(*n*) operation as it requires copying every element in the
1340 /// buffer.
1341 ///
1342 /// # Panics
1343 ///
1344 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1345 /// lie on a [`char`] boundary.
1346 ///
1347 /// # Examples
1348 ///
1349 /// ```
1350 /// use rune::alloc::String;
1351 ///
1352 /// let mut s = String::try_from("bar")?;
1353 ///
1354 /// s.try_insert_str(0, "foo")?;
1355 ///
1356 /// assert_eq!("foobar", s);
1357 /// # Ok::<_, rune::alloc::Error>(())
1358 /// ```
1359 #[inline]
1360 pub fn try_insert_str(&mut self, idx: usize, string: &str) -> Result<(), Error> {
1361 assert!(self.is_char_boundary(idx));
1362
1363 unsafe {
1364 self.insert_bytes(idx, string.as_bytes())?;
1365 }
1366
1367 Ok(())
1368 }
1369
1370 /// Returns a mutable reference to the contents of this `String`.
1371 ///
1372 /// # Safety
1373 ///
1374 /// This function is unsafe because the returned `&mut Vec` allows writing
1375 /// bytes which are not valid UTF-8. If this constraint is violated, using
1376 /// the original `String` after dropping the `&mut Vec` may violate memory
1377 /// safety, as the rest of the standard library assumes that `String`s are
1378 /// valid UTF-8.
1379 ///
1380 /// # Examples
1381 ///
1382 /// ```
1383 /// use rune::alloc::String;
1384 ///
1385 /// let mut s = String::try_from("hello")?;
1386 ///
1387 /// unsafe {
1388 /// let vec = s.as_mut_vec();
1389 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1390 ///
1391 /// vec.reverse();
1392 /// }
1393 /// assert_eq!(s, "olleh");
1394 /// # Ok::<_, rune::alloc::Error>(())
1395 /// ```
1396 #[inline]
1397 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8, A> {
1398 &mut self.vec
1399 }
1400
1401 /// Returns the length of this `String`, in bytes, not [`char`]s or
1402 /// graphemes. In other words, it might not be what a human considers the
1403 /// length of the string.
1404 ///
1405 /// # Examples
1406 ///
1407 /// ```
1408 /// use rune::alloc::String;
1409 ///
1410 /// let a = String::try_from("foo")?;
1411 /// assert_eq!(a.len(), 3);
1412 ///
1413 /// let fancy_f = String::try_from("Ζoo")?;
1414 /// assert_eq!(fancy_f.len(), 4);
1415 /// assert_eq!(fancy_f.chars().count(), 3);
1416 /// # Ok::<_, rune::alloc::Error>(())
1417 /// ```
1418 #[inline]
1419 #[must_use]
1420 pub fn len(&self) -> usize {
1421 self.vec.len()
1422 }
1423
1424 /// Returns `true` if this `String` has a length of zero, and `false`
1425 /// otherwise.
1426 ///
1427 /// # Examples
1428 ///
1429 /// ```
1430 /// use rune::alloc::String;
1431 ///
1432 /// let mut v = String::new();
1433 /// assert!(v.is_empty());
1434 ///
1435 /// v.try_push('a')?;
1436 /// assert!(!v.is_empty());
1437 /// # Ok::<_, rune::alloc::Error>(())
1438 /// ```
1439 #[inline]
1440 #[must_use]
1441 pub fn is_empty(&self) -> bool {
1442 self.len() == 0
1443 }
1444
1445 /// Splits the string into two at the given byte index.
1446 ///
1447 /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1448 /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1449 /// boundary of a UTF-8 code point.
1450 ///
1451 /// Note that the capacity of `self` does not change.
1452 ///
1453 /// # Panics
1454 ///
1455 /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1456 /// code point of the string.
1457 ///
1458 /// # Examples
1459 ///
1460 /// ```
1461 /// use rune::alloc::String;
1462 ///
1463 /// let mut hello = String::try_from("Hello, World!")?;
1464 /// let world = hello.try_split_off(7)?;
1465 /// assert_eq!(hello, "Hello, ");
1466 /// assert_eq!(world, "World!");
1467 /// # Ok::<_, rune::alloc::Error>(())
1468 /// ```
1469 #[inline]
1470 #[must_use = "use `.truncate()` if you don't need the other half"]
1471 pub fn try_split_off(&mut self, at: usize) -> Result<String<A>, Error>
1472 where
1473 A: Clone,
1474 {
1475 assert!(self.is_char_boundary(at));
1476 let other = self.vec.try_split_off(at)?;
1477 Ok(unsafe { String::from_utf8_unchecked(other) })
1478 }
1479
1480 /// Truncates this `String`, removing all contents.
1481 ///
1482 /// While this means the `String` will have a length of zero, it does not
1483 /// touch its capacity.
1484 ///
1485 /// # Examples
1486 ///
1487 /// ```
1488 /// use rune::alloc::String;
1489 ///
1490 /// let mut s = String::try_from("foo")?;
1491 ///
1492 /// s.clear();
1493 ///
1494 /// assert!(s.is_empty());
1495 /// assert_eq!(0, s.len());
1496 /// assert_eq!(3, s.capacity());
1497 /// # Ok::<_, rune::alloc::Error>(())
1498 /// ```
1499 #[inline]
1500 pub fn clear(&mut self) {
1501 self.vec.clear()
1502 }
1503
1504 /// Removes the specified range from the string in bulk, returning all
1505 /// removed characters as an iterator.
1506 ///
1507 /// The returned iterator keeps a mutable borrow on the string to optimize
1508 /// its implementation.
1509 ///
1510 /// # Panics
1511 ///
1512 /// Panics if the starting point or end point do not lie on a [`char`]
1513 /// boundary, or if they're out of bounds.
1514 ///
1515 /// # Leaking
1516 ///
1517 /// If the returned iterator goes out of scope without being dropped (due to
1518 /// [`core::mem::forget`], for example), the string may still contain a copy
1519 /// of any drained characters, or may have lost characters arbitrarily,
1520 /// including characters outside the range.
1521 ///
1522 /// # Examples
1523 ///
1524 /// ```
1525 /// use rune::alloc::String;
1526 /// use rune::alloc::prelude::*;
1527 ///
1528 /// let mut s = String::try_from("Ξ± is alpha, Ξ² is beta")?;
1529 /// let beta_offset = s.find('Ξ²').unwrap_or(s.len());
1530 ///
1531 /// // Remove the range up until the Ξ² from the string
1532 /// let t: String = s.drain(..beta_offset).try_collect()?;
1533 /// assert_eq!(t, "Ξ± is alpha, ");
1534 /// assert_eq!(s, "Ξ² is beta");
1535 ///
1536 /// // A full range clears the string, like `clear()` does
1537 /// s.drain(..);
1538 /// assert_eq!(s, "");
1539 /// # Ok::<_, rune::alloc::Error>(())
1540 /// ```
1541 pub fn drain<R>(&mut self, range: R) -> Drain<'_, A>
1542 where
1543 R: RangeBounds<usize>,
1544 {
1545 // Memory safety
1546 //
1547 // The String version of Drain does not have the memory safety issues
1548 // of the vector version. The data is just plain bytes.
1549 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1550 // the removal will not happen.
1551 let Range { start, end } = slice_range(range, ..self.len());
1552 assert!(self.is_char_boundary(start));
1553 assert!(self.is_char_boundary(end));
1554
1555 // Take out two simultaneous borrows. The &mut String won't be accessed
1556 // until iteration is over, in Drop.
1557 let self_ptr = self as *mut _;
1558 // SAFETY: `slice::range` and `is_char_boundary` do the appropriate bounds checks.
1559 let chars_iter = unsafe { self.get_unchecked(start..end) }.chars();
1560
1561 Drain {
1562 start,
1563 end,
1564 iter: chars_iter,
1565 string: self_ptr,
1566 }
1567 }
1568
1569 /// Removes the specified range in the string,
1570 /// and replaces it with the given string.
1571 /// The given string doesn't need to be the same length as the range.
1572 ///
1573 /// # Panics
1574 ///
1575 /// Panics if the starting point or end point do not lie on a [`char`]
1576 /// boundary, or if they're out of bounds.
1577 ///
1578 /// # Examples
1579 ///
1580 /// ```
1581 /// use rune::alloc::String;
1582 ///
1583 /// let mut s = String::try_from("Ξ± is alpha, Ξ² is beta")?;
1584 /// let beta_offset = s.find('Ξ²').unwrap_or(s.len());
1585 ///
1586 /// // Replace the range up until the Ξ² from the string
1587 /// s.try_replace_range(..beta_offset, "Ξ is capital alpha; ")?;
1588 /// assert_eq!(s, "Ξ is capital alpha; Ξ² is beta");
1589 /// # Ok::<_, rune::alloc::Error>(())
1590 /// ```
1591 pub fn try_replace_range<R>(&mut self, range: R, replace_with: &str) -> Result<(), Error>
1592 where
1593 R: RangeBounds<usize>,
1594 {
1595 // Memory safety
1596 //
1597 // Replace_range does not have the memory safety issues of a vector Splice.
1598 // of the vector version. The data is just plain bytes.
1599
1600 // WARNING: Inlining this variable would be unsound (#81138)
1601 let start = range.start_bound();
1602 match start {
1603 Included(&n) => assert!(self.is_char_boundary(n)),
1604 Excluded(&n) => assert!(self.is_char_boundary(n + 1)),
1605 Unbounded => {}
1606 };
1607 // WARNING: Inlining this variable would be unsound (#81138)
1608 let end = range.end_bound();
1609 match end {
1610 Included(&n) => assert!(self.is_char_boundary(n + 1)),
1611 Excluded(&n) => assert!(self.is_char_boundary(n)),
1612 Unbounded => {}
1613 };
1614
1615 // Using `range` again would be unsound (#81138)
1616 // We assume the bounds reported by `range` remain the same, but
1617 // an adversarial implementation could change between calls
1618 unsafe { self.as_mut_vec() }.try_splice_in_place((start, end), replace_with.bytes())?;
1619 Ok(())
1620 }
1621
1622 /// Converts this `String` into a <code>[Box]<[str]></code>.
1623 ///
1624 /// This will drop any excess capacity.
1625 ///
1626 /// [str]: prim@str "str"
1627 ///
1628 /// # Examples
1629 ///
1630 /// ```
1631 /// use rune::alloc::String;
1632 /// let s = String::try_from("hello")?;
1633 ///
1634 /// let b = s.try_into_boxed_str()?;
1635 /// # Ok::<_, rune::alloc::Error>(())
1636 /// ```
1637 #[must_use = "`self` will be dropped if the result is not used"]
1638 #[inline]
1639 pub fn try_into_boxed_str(self) -> Result<Box<str, A>, Error> {
1640 let slice = self.vec.try_into_boxed_slice()?;
1641 Ok(unsafe { crate::str::from_boxed_utf8_unchecked(slice) })
1642 }
1643
1644 /// Consumes and leaks the `String`, returning a mutable reference to the contents,
1645 /// `&'a mut str`.
1646 ///
1647 /// The caller has free choice over the returned lifetime, including `'static`. Indeed,
1648 /// this function is ideally used for data that lives for the remainder of the program's life,
1649 /// as dropping the returned reference will cause a memory leak.
1650 ///
1651 /// It does not reallocate or shrink the `String`,
1652 /// so the leaked allocation may include unused capacity that is not part
1653 /// of the returned slice. If you don't want that, call [`try_into_boxed_str`],
1654 /// and then [`Box::leak`].
1655 ///
1656 /// [`try_into_boxed_str`]: Self::try_into_boxed_str
1657 ///
1658 /// # Examples
1659 ///
1660 /// ```
1661 /// # #[cfg(not(miri))]
1662 /// # fn main() -> Result<(), rune_alloc::Error> {
1663 /// use rune::alloc::String;
1664 ///
1665 /// let x = String::try_from("bucket")?;
1666 /// let static_ref: &'static mut str = x.leak();
1667 /// assert_eq!(static_ref, "bucket");
1668 /// # Ok(())
1669 /// # }
1670 /// # #[cfg(miri)] fn main() {}
1671 /// ```
1672 #[inline]
1673 pub fn leak<'a>(self) -> &'a mut str
1674 where
1675 A: 'a,
1676 {
1677 let slice = self.vec.leak();
1678 unsafe { from_utf8_unchecked_mut(slice) }
1679 }
1680}
1681
1682impl<A> FromUtf8Error<A>
1683where
1684 A: Allocator,
1685{
1686 /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
1687 ///
1688 /// # Examples
1689 ///
1690 /// ```
1691 /// use rune::alloc::{try_vec, String};
1692 ///
1693 /// // some invalid bytes, in a vector
1694 /// let bytes = try_vec![0, 159];
1695 ///
1696 /// let value = String::from_utf8(bytes);
1697 ///
1698 /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1699 /// # Ok::<_, rune::alloc::Error>(())
1700 /// ```
1701 #[must_use]
1702 pub fn as_bytes(&self) -> &[u8] {
1703 &self.bytes[..]
1704 }
1705
1706 /// Returns the bytes that were attempted to convert to a `String`.
1707 ///
1708 /// This method is carefully constructed to avoid allocation. It will
1709 /// consume the error, moving out the bytes, so that a copy of the bytes
1710 /// does not need to be made.
1711 ///
1712 /// # Examples
1713 ///
1714 /// ```
1715 /// use rune::alloc::{try_vec, String};
1716 ///
1717 /// // some invalid bytes, in a vector
1718 /// let bytes = try_vec![0, 159];
1719 ///
1720 /// let value = String::from_utf8(bytes);
1721 ///
1722 /// assert_eq!(try_vec![0, 159], value.unwrap_err().into_bytes());
1723 /// # Ok::<_, rune::alloc::Error>(())
1724 /// ```
1725 #[must_use = "`self` will be dropped if the result is not used"]
1726 pub fn into_bytes(self) -> Vec<u8, A> {
1727 self.bytes
1728 }
1729
1730 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1731 ///
1732 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that
1733 /// may occur when converting a slice of [`u8`]s to a [`&str`]. In this
1734 /// sense, it's an analogue to `FromUtf8Error`. See its documentation for
1735 /// more details on using it.
1736 ///
1737 /// [`std::str`]: core::str "std::str"
1738 /// [`&str`]: prim@str "&str"
1739 ///
1740 /// # Examples
1741 ///
1742 /// ```
1743 /// use rune::alloc::{try_vec, String};
1744 ///
1745 /// // some invalid bytes, in a vector
1746 /// let bytes = try_vec![0, 159];
1747 ///
1748 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1749 ///
1750 /// // the first byte is invalid here
1751 /// assert_eq!(1, error.valid_up_to());
1752 /// # Ok::<_, rune::alloc::Error>(())
1753 /// ```
1754 #[must_use]
1755 pub fn utf8_error(&self) -> Utf8Error {
1756 self.error
1757 }
1758}
1759
1760impl<A> Default for String<A>
1761where
1762 A: Allocator + Default,
1763{
1764 /// Construct a default string.
1765 ///
1766 /// # Examples
1767 ///
1768 /// ```
1769 /// use rune::alloc::String;
1770 /// let s = String::default();
1771 /// assert_eq!(s, "");
1772 /// ```
1773 fn default() -> Self {
1774 Self::new_in(A::default())
1775 }
1776}
1777
1778impl<A> Borrow<str> for String<A>
1779where
1780 A: Allocator,
1781{
1782 #[inline]
1783 fn borrow(&self) -> &str {
1784 &self[..]
1785 }
1786}
1787
1788impl<A> fmt::Display for FromUtf8Error<A>
1789where
1790 A: Allocator,
1791{
1792 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1793 fmt::Display::fmt(&self.error, f)
1794 }
1795}
1796
1797impl<A> core::error::Error for FromUtf8Error<A> where A: Allocator {}
1798
1799impl<A> TryClone for String<A>
1800where
1801 A: Allocator + Clone,
1802{
1803 fn try_clone(&self) -> Result<Self, Error> {
1804 Ok(String {
1805 vec: self.vec.try_clone()?,
1806 })
1807 }
1808}
1809
1810#[cfg(test)]
1811impl<A> Clone for String<A>
1812where
1813 A: Allocator + Clone,
1814{
1815 fn clone(&self) -> Self {
1816 self.try_clone().abort()
1817 }
1818}
1819
1820impl<A> PartialEq for String<A>
1821where
1822 A: Allocator,
1823{
1824 #[inline]
1825 fn eq(&self, other: &Self) -> bool {
1826 self.vec == other.vec
1827 }
1828}
1829
1830impl<A> Eq for String<A> where A: Allocator {}
1831
1832impl<A> PartialOrd for String<A>
1833where
1834 A: Allocator,
1835{
1836 #[inline]
1837 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1838 Some(self.cmp(other))
1839 }
1840}
1841
1842impl<A> Ord for String<A>
1843where
1844 A: Allocator,
1845{
1846 #[inline]
1847 fn cmp(&self, other: &Self) -> Ordering {
1848 self.vec.cmp(&other.vec)
1849 }
1850}
1851
1852macro_rules! impl_eq {
1853 ($lhs:ty, $rhs: ty) => {
1854 #[allow(unused_lifetimes)]
1855 #[allow(clippy::partialeq_ne_impl)]
1856 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1857 #[inline]
1858 fn eq(&self, other: &$rhs) -> bool {
1859 PartialEq::eq(&self[..], &other[..])
1860 }
1861 #[inline]
1862 fn ne(&self, other: &$rhs) -> bool {
1863 PartialEq::ne(&self[..], &other[..])
1864 }
1865 }
1866
1867 #[allow(unused_lifetimes)]
1868 #[allow(clippy::partialeq_ne_impl)]
1869 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1870 #[inline]
1871 fn eq(&self, other: &$lhs) -> bool {
1872 PartialEq::eq(&self[..], &other[..])
1873 }
1874 #[inline]
1875 fn ne(&self, other: &$lhs) -> bool {
1876 PartialEq::ne(&self[..], &other[..])
1877 }
1878 }
1879 };
1880}
1881
1882impl_eq! { String, str }
1883impl_eq! { String, &'a str }
1884impl_eq! { Cow<'a, str>, str }
1885impl_eq! { Cow<'a, str>, &'b str }
1886impl_eq! { Cow<'a, str>, String }
1887
1888impl<A> fmt::Display for String<A>
1889where
1890 A: Allocator,
1891{
1892 #[inline]
1893 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1894 fmt::Display::fmt(&**self, f)
1895 }
1896}
1897
1898impl<A> fmt::Debug for String<A>
1899where
1900 A: Allocator,
1901{
1902 #[inline]
1903 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1904 fmt::Debug::fmt(&**self, f)
1905 }
1906}
1907
1908impl<A> hash::Hash for String<A>
1909where
1910 A: Allocator,
1911{
1912 #[inline]
1913 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1914 (**self).hash(hasher)
1915 }
1916}
1917
1918impl<A> ops::Index<ops::Range<usize>> for String<A>
1919where
1920 A: Allocator,
1921{
1922 type Output = str;
1923
1924 #[inline]
1925 fn index(&self, index: ops::Range<usize>) -> &str {
1926 &self[..][index]
1927 }
1928}
1929
1930impl<A> ops::Index<ops::RangeTo<usize>> for String<A>
1931where
1932 A: Allocator,
1933{
1934 type Output = str;
1935
1936 #[inline]
1937 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1938 &self[..][index]
1939 }
1940}
1941
1942impl<A> ops::Index<ops::RangeFrom<usize>> for String<A>
1943where
1944 A: Allocator,
1945{
1946 type Output = str;
1947
1948 #[inline]
1949 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1950 &self[..][index]
1951 }
1952}
1953
1954impl<A> ops::Index<ops::RangeFull> for String<A>
1955where
1956 A: Allocator,
1957{
1958 type Output = str;
1959
1960 #[inline]
1961 fn index(&self, _index: ops::RangeFull) -> &str {
1962 unsafe { from_utf8_unchecked(&self.vec) }
1963 }
1964}
1965
1966impl<A> ops::Index<ops::RangeInclusive<usize>> for String<A>
1967where
1968 A: Allocator,
1969{
1970 type Output = str;
1971
1972 #[inline]
1973 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1974 Index::index(&**self, index)
1975 }
1976}
1977
1978impl<A> ops::Index<ops::RangeToInclusive<usize>> for String<A>
1979where
1980 A: Allocator,
1981{
1982 type Output = str;
1983
1984 #[inline]
1985 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1986 Index::index(&**self, index)
1987 }
1988}
1989
1990impl<A> ops::IndexMut<ops::Range<usize>> for String<A>
1991where
1992 A: Allocator,
1993{
1994 #[inline]
1995 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1996 &mut self[..][index]
1997 }
1998}
1999
2000impl<A> ops::IndexMut<ops::RangeTo<usize>> for String<A>
2001where
2002 A: Allocator,
2003{
2004 #[inline]
2005 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
2006 &mut self[..][index]
2007 }
2008}
2009
2010impl<A> ops::IndexMut<ops::RangeFrom<usize>> for String<A>
2011where
2012 A: Allocator,
2013{
2014 #[inline]
2015 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
2016 &mut self[..][index]
2017 }
2018}
2019
2020impl<A> ops::IndexMut<ops::RangeFull> for String<A>
2021where
2022 A: Allocator,
2023{
2024 #[inline]
2025 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
2026 unsafe { from_utf8_unchecked_mut(&mut self.vec) }
2027 }
2028}
2029
2030impl<A> ops::IndexMut<ops::RangeInclusive<usize>> for String<A>
2031where
2032 A: Allocator,
2033{
2034 #[inline]
2035 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
2036 IndexMut::index_mut(&mut **self, index)
2037 }
2038}
2039
2040impl<A> ops::IndexMut<ops::RangeToInclusive<usize>> for String<A>
2041where
2042 A: Allocator,
2043{
2044 #[inline]
2045 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
2046 IndexMut::index_mut(&mut **self, index)
2047 }
2048}
2049
2050impl<A> ops::Deref for String<A>
2051where
2052 A: Allocator,
2053{
2054 type Target = str;
2055
2056 #[inline]
2057 fn deref(&self) -> &str {
2058 unsafe { from_utf8_unchecked(&self.vec) }
2059 }
2060}
2061
2062impl<A> ops::DerefMut for String<A>
2063where
2064 A: Allocator,
2065{
2066 #[inline]
2067 fn deref_mut(&mut self) -> &mut str {
2068 unsafe { from_utf8_unchecked_mut(&mut self.vec) }
2069 }
2070}
2071
2072impl<A> AsRef<str> for String<A>
2073where
2074 A: Allocator,
2075{
2076 #[inline]
2077 fn as_ref(&self) -> &str {
2078 self
2079 }
2080}
2081
2082impl<A> AsMut<str> for String<A>
2083where
2084 A: Allocator,
2085{
2086 #[inline]
2087 fn as_mut(&mut self) -> &mut str {
2088 self
2089 }
2090}
2091
2092#[cfg(feature = "std")]
2093impl<A> AsRef<std::ffi::OsStr> for String<A>
2094where
2095 A: Allocator,
2096{
2097 #[inline]
2098 fn as_ref(&self) -> &std::ffi::OsStr {
2099 (**self).as_ref()
2100 }
2101}
2102
2103impl<A> AsRef<[u8]> for String<A>
2104where
2105 A: Allocator,
2106{
2107 #[inline]
2108 fn as_ref(&self) -> &[u8] {
2109 self.as_bytes()
2110 }
2111}
2112
2113impl<A> From<Box<str, A>> for String<A>
2114where
2115 A: Allocator,
2116{
2117 /// Converts the given boxed `str` slice to a [`String`].
2118 /// It is notable that the `str` slice is owned.
2119 ///
2120 /// # Examples
2121 ///
2122 /// Basic usage:
2123 ///
2124 /// ```
2125 /// use rune::alloc::{Box, String};
2126 ///
2127 /// let s1: String = String::try_from("hello world")?;
2128 /// let s2: Box<str> = s1.try_into_boxed_str()?;
2129 /// let s3: String = String::from(s2);
2130 ///
2131 /// assert_eq!("hello world", s3);
2132 /// # Ok::<_, rune::alloc::Error>(())
2133 /// ```
2134 fn from(s: Box<str, A>) -> String<A> {
2135 crate::str::into_string(s)
2136 }
2137}
2138
2139#[cfg(feature = "alloc")]
2140impl TryFrom<rust_alloc::boxed::Box<str>> for String<Global> {
2141 type Error = Error;
2142
2143 /// Try to convert a std `Box<str>` into a [`String`].
2144 ///
2145 /// The result is fallibly allocated on the heap.
2146 fn try_from(s: rust_alloc::boxed::Box<str>) -> Result<Self, Error> {
2147 Self::try_from(s.as_ref())
2148 }
2149}
2150
2151#[cfg(feature = "alloc")]
2152impl TryFrom<rust_alloc::string::String> for String<Global> {
2153 type Error = Error;
2154
2155 /// Try to convert a std `String` into a [`String`].
2156 ///
2157 /// The result is fallibly allocated on the heap.
2158 ///
2159 /// # Examples
2160 ///
2161 /// ```
2162 /// use rune::alloc;
2163 ///
2164 /// let s1 = String::from("Hello World");
2165 /// let s2 = alloc::String::try_from(s1)?;
2166 ///
2167 /// assert_eq!("Hello World", s2);
2168 /// # Ok::<_, rune::alloc::Error>(())
2169 /// ```
2170 fn try_from(string: rust_alloc::string::String) -> Result<Self, Error> {
2171 let mut string = ManuallyDrop::new(string.into_bytes());
2172
2173 let buf = string.as_mut_ptr();
2174 let length = string.len();
2175 let capacity = string.capacity();
2176
2177 if let Ok(layout) = Layout::array::<u8>(capacity) {
2178 Global.take(layout)?;
2179 }
2180
2181 // SAFETY: The layout of the string is identical to the std string and
2182 // it uses the same underlying allocator.
2183 unsafe { Ok(String::from_raw_parts_in(buf, length, capacity, Global)) }
2184 }
2185}
2186
2187#[cfg(feature = "alloc")]
2188impl<A> From<String<A>> for rust_alloc::string::String
2189where
2190 A: Allocator,
2191{
2192 /// Try to convert a [`String`] into a std `String`.
2193 ///
2194 /// The result is allocated on the heap.
2195 fn from(s: String<A>) -> Self {
2196 Self::from(s.as_str())
2197 }
2198}
2199
2200#[cfg(feature = "alloc")]
2201impl<A> From<&String<A>> for rust_alloc::string::String
2202where
2203 A: Allocator,
2204{
2205 /// Try to convert a [`String`] reference into a std `String`.
2206 ///
2207 /// The result is allocated on the heap.
2208 fn from(s: &String<A>) -> Self {
2209 Self::from(s.as_str())
2210 }
2211}
2212
2213impl TryFrom<&str> for String<Global> {
2214 type Error = Error;
2215
2216 /// Converts a `&str` into a [`String`].
2217 ///
2218 /// The result is fallibly allocated on the heap.
2219 ///
2220 /// ```
2221 /// use rune::alloc::String;
2222 ///
2223 /// let s = String::try_from("Hello World")?;
2224 /// assert_eq!(s, "Hello World");
2225 /// # Ok::<_, rune::alloc::Error>(())
2226 /// ```
2227 fn try_from(s: &str) -> Result<Self, Error> {
2228 let mut out = String::try_with_capacity_in(s.len(), Global)?;
2229 out.try_push_str(s)?;
2230 Ok(out)
2231 }
2232}
2233
2234impl TryFrom<Cow<'_, str>> for String<Global> {
2235 type Error = Error;
2236
2237 /// Converts a `Cow<str>` into a [`String`].
2238 ///
2239 /// The result is fallibly allocated on the heap unless the values is
2240 /// `Cow::Owned`.
2241 ///
2242 /// ```
2243 /// use rune::alloc::String;
2244 /// use rune::alloc::borrow::Cow;
2245 ///
2246 /// let s = Cow::Borrowed("Hello World");
2247 /// let s = String::try_from(s)?;
2248 /// assert_eq!(s, "Hello World");
2249 ///
2250 /// let s = Cow::Owned(String::try_from("Hello World")?);
2251 /// let s = String::try_from(s)?;
2252 /// assert_eq!(s, "Hello World");
2253 /// # Ok::<_, rune::alloc::Error>(())
2254 /// ```
2255 fn try_from(s: Cow<'_, str>) -> Result<Self, Error> {
2256 match s {
2257 Cow::Borrowed(s) => Self::try_from(s),
2258 Cow::Owned(s) => Ok(s),
2259 }
2260 }
2261}
2262
2263impl<A: Allocator + Clone> TryFrom<&String<A>> for String<A> {
2264 type Error = Error;
2265
2266 /// Converts the given [`String`] to a boxed `str` slice that is owned.
2267 ///
2268 /// # Examples
2269 ///
2270 /// ```
2271 /// use rune::alloc::{String, Box};
2272 ///
2273 /// let s1: String = String::try_from("Hello World")?;
2274 /// let s2: String = String::try_from(&s1)?;
2275 ///
2276 /// assert_eq!(s2, "Hello World");
2277 /// # Ok::<_, rune::alloc::Error>(())
2278 /// ```
2279 #[inline]
2280 fn try_from(s: &String<A>) -> Result<Self, Error> {
2281 let mut this = String::new_in(s.allocator().clone());
2282 this.try_push_str(s.as_str())?;
2283 Ok(this)
2284 }
2285}
2286
2287impl<A> TryFrom<String<A>> for Box<str, A>
2288where
2289 A: Allocator,
2290{
2291 type Error = Error;
2292
2293 /// Converts the given [`String`] to a boxed `str` slice that is owned.
2294 ///
2295 /// # Examples
2296 ///
2297 /// ```
2298 /// use rune::alloc::{String, Box};
2299 ///
2300 /// let s1: String = String::try_from("Hello World")?;
2301 /// let s2: Box<str> = Box::try_from("Hello World")?;
2302 ///
2303 /// assert_eq!("Hello World", s2.as_ref());
2304 /// # Ok::<_, rune::alloc::Error>(())
2305 /// ```
2306 #[inline]
2307 fn try_from(s: String<A>) -> Result<Self, Error> {
2308 s.try_into_boxed_str()
2309 }
2310}
2311
2312impl TryFrom<Cow<'_, str>> for Box<str> {
2313 type Error = Error;
2314
2315 /// Converts the given [`String`] to a boxed `str` slice that is owned.
2316 ///
2317 /// # Examples
2318 ///
2319 /// ```
2320 /// use rune::alloc::Box;
2321 /// use rune::alloc::borrow::Cow;
2322 ///
2323 /// let s2: Box<str> = Box::try_from(Cow::Borrowed("Hello World"))?;
2324 ///
2325 /// assert_eq!("Hello World", s2.as_ref());
2326 /// # Ok::<_, rune::alloc::Error>(())
2327 /// ```
2328 #[inline]
2329 fn try_from(s: Cow<'_, str>) -> Result<Self, Error> {
2330 Self::try_from(s.as_ref())
2331 }
2332}
2333
2334impl<A> From<String<A>> for Vec<u8, A>
2335where
2336 A: Allocator,
2337{
2338 /// Converts the given [`String`] to a vector [`Vec`] that holds values of type [`u8`].
2339 ///
2340 /// # Examples
2341 ///
2342 /// ```
2343 /// use rune::alloc::{String, Vec};
2344 ///
2345 /// let s1 = String::try_from("hello world")?;
2346 /// let v1 = Vec::from(s1);
2347 ///
2348 /// for b in v1 {
2349 /// println!("{b}");
2350 /// }
2351 /// # Ok::<_, rune::alloc::Error>(())
2352 /// ```
2353 #[inline]
2354 fn from(string: String<A>) -> Vec<u8, A> {
2355 string.into_bytes()
2356 }
2357}
2358
2359/// A draining iterator for `String`.
2360///
2361/// This struct is created by the [`drain`] method on [`String`]. See its
2362/// documentation for more.
2363///
2364/// [`drain`]: String::drain
2365pub struct Drain<'a, A>
2366where
2367 A: Allocator,
2368{
2369 /// Will be used as &'a mut String in the destructor
2370 string: *mut String<A>,
2371 /// Start of part to remove
2372 start: usize,
2373 /// End of part to remove
2374 end: usize,
2375 /// Current remaining range to remove
2376 iter: Chars<'a>,
2377}
2378
2379impl<A> fmt::Debug for Drain<'_, A>
2380where
2381 A: Allocator,
2382{
2383 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2384 f.debug_tuple("Drain").field(&self.as_str()).finish()
2385 }
2386}
2387
2388unsafe impl<A> Sync for Drain<'_, A> where A: Allocator {}
2389unsafe impl<A> Send for Drain<'_, A> where A: Allocator {}
2390
2391impl<A> Drop for Drain<'_, A>
2392where
2393 A: Allocator,
2394{
2395 fn drop(&mut self) {
2396 unsafe {
2397 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2398 // panic code being inserted again.
2399 let self_vec = (*self.string).as_mut_vec();
2400
2401 if self.start <= self.end && self.end <= self_vec.len() {
2402 self_vec.drain(self.start..self.end);
2403 }
2404 }
2405 }
2406}
2407
2408impl<A> Drain<'_, A>
2409where
2410 A: Allocator,
2411{
2412 /// Returns the remaining (sub)string of this iterator as a slice.
2413 ///
2414 /// # Examples
2415 ///
2416 /// ```
2417 /// use rune::alloc::String;
2418 ///
2419 /// let mut s = String::try_from("abc")?;
2420 /// let mut drain = s.drain(..);
2421 /// assert_eq!(drain.as_str(), "abc");
2422 /// assert!(drain.next().is_some());
2423 /// assert_eq!(drain.as_str(), "bc");
2424 /// # Ok::<_, rune::alloc::Error>(())
2425 /// ```
2426 #[must_use]
2427 pub fn as_str(&self) -> &str {
2428 self.iter.as_str()
2429 }
2430}
2431
2432impl<A> AsRef<str> for Drain<'_, A>
2433where
2434 A: Allocator,
2435{
2436 fn as_ref(&self) -> &str {
2437 self.as_str()
2438 }
2439}
2440
2441impl<A> AsRef<[u8]> for Drain<'_, A>
2442where
2443 A: Allocator,
2444{
2445 fn as_ref(&self) -> &[u8] {
2446 self.as_str().as_bytes()
2447 }
2448}
2449
2450impl<A> Iterator for Drain<'_, A>
2451where
2452 A: Allocator,
2453{
2454 type Item = char;
2455
2456 #[inline]
2457 fn next(&mut self) -> Option<char> {
2458 self.iter.next()
2459 }
2460
2461 fn size_hint(&self) -> (usize, Option<usize>) {
2462 self.iter.size_hint()
2463 }
2464
2465 #[inline]
2466 fn last(mut self) -> Option<char> {
2467 self.next_back()
2468 }
2469}
2470
2471impl<A> DoubleEndedIterator for Drain<'_, A>
2472where
2473 A: Allocator,
2474{
2475 #[inline]
2476 fn next_back(&mut self) -> Option<char> {
2477 self.iter.next_back()
2478 }
2479}
2480
2481impl<A> FusedIterator for Drain<'_, A> where A: Allocator {}
2482
2483impl<A> TryWrite for String<A>
2484where
2485 A: Allocator,
2486{
2487 #[inline]
2488 fn try_write_str(&mut self, s: &str) -> Result<(), Error> {
2489 self.try_push_str(s)
2490 }
2491
2492 #[inline]
2493 fn try_write_char(&mut self, c: char) -> Result<(), Error> {
2494 self.try_push(c)
2495 }
2496}
2497
2498impl<A> TryFromIteratorIn<char, A> for String<A>
2499where
2500 A: Allocator,
2501{
2502 /// Construct a string from an iterator of characters.
2503 ///
2504 /// ```
2505 /// use rune::alloc::String;
2506 /// use rune::alloc::prelude::*;
2507 ///
2508 /// let string = String::try_from_iter(['a', 'b', 'c'].into_iter())?;
2509 /// assert_eq!(string, "abc");
2510 /// # Ok::<_, rune::alloc::Error>(())
2511 /// ```
2512 fn try_from_iter_in<I>(iter: I, alloc: A) -> Result<Self, Error>
2513 where
2514 I: IntoIterator<Item = char>,
2515 {
2516 let mut this = String::new_in(alloc);
2517 this.try_extend(iter)?;
2518 Ok(this)
2519 }
2520}
2521
2522impl<'a, A> TryFromIteratorIn<&'a str, A> for String<A>
2523where
2524 A: Allocator,
2525{
2526 /// Construct a string from an iterator of characters.
2527 ///
2528 /// ```
2529 /// use rune::alloc::String;
2530 /// use rune::alloc::prelude::*;
2531 ///
2532 /// let string = String::try_from_iter(["hello", " ", "world"].into_iter())?;
2533 /// assert_eq!(string, "hello world");
2534 /// # Ok::<_, rune::alloc::Error>(())
2535 /// ```
2536 fn try_from_iter_in<I>(iter: I, alloc: A) -> Result<Self, Error>
2537 where
2538 I: IntoIterator<Item = &'a str>,
2539 {
2540 let mut this = String::new_in(alloc);
2541 this.try_extend(iter)?;
2542 Ok(this)
2543 }
2544}
2545
2546impl<T, A> TryJoin<char, T, A> for String<A>
2547where
2548 T: AsRef<str>,
2549 A: Allocator,
2550{
2551 fn try_join_in<I>(iter: I, sep: char, alloc: A) -> Result<Self, Error>
2552 where
2553 I: IntoIterator<Item = T>,
2554 {
2555 let mut string = String::new_in(alloc);
2556
2557 let mut iter = iter.into_iter().peekable();
2558
2559 while let Some(value) = iter.next() {
2560 string.try_push_str(value.as_ref())?;
2561
2562 if iter.peek().is_some() {
2563 string.try_push(sep)?;
2564 }
2565 }
2566
2567 Ok(string)
2568 }
2569}
2570
2571impl<T, A> TryJoin<&str, T, A> for String<A>
2572where
2573 T: AsRef<str>,
2574 A: Allocator,
2575{
2576 fn try_join_in<I>(iter: I, sep: &str, alloc: A) -> Result<Self, Error>
2577 where
2578 I: IntoIterator<Item = T>,
2579 {
2580 let mut string = String::new_in(alloc);
2581
2582 let mut iter = iter.into_iter().peekable();
2583
2584 while let Some(value) = iter.next() {
2585 string.try_push_str(value.as_ref())?;
2586
2587 if iter.peek().is_some() {
2588 string.try_push_str(sep)?;
2589 }
2590 }
2591
2592 Ok(string)
2593 }
2594}
2595
2596impl<A> TryExtend<char> for String<A>
2597where
2598 A: Allocator,
2599{
2600 /// Extend a string using a character iterator.
2601 ///
2602 /// ```
2603 /// use rune::alloc::String;
2604 /// use rune::alloc::prelude::*;
2605 ///
2606 /// let mut string = String::new();
2607 /// string.try_extend(['a', 'b', 'c'])?;
2608 /// assert_eq!(string, "abc");
2609 /// # Ok::<_, rune::alloc::Error>(())
2610 /// ```
2611 #[inline]
2612 fn try_extend<I: IntoIterator<Item = char>>(&mut self, iter: I) -> Result<(), Error> {
2613 for value in iter {
2614 self.try_push(value)?;
2615 }
2616
2617 Ok(())
2618 }
2619}
2620
2621impl<'a, A> TryExtend<&'a str> for String<A>
2622where
2623 A: Allocator,
2624{
2625 /// Extend a string using a character iterator.
2626 ///
2627 /// ```
2628 /// use rune::alloc::String;
2629 /// use rune::alloc::prelude::*;
2630 ///
2631 /// let mut string = String::new();
2632 /// string.try_extend(["hello", " ", "world"])?;
2633 /// assert_eq!(string, "hello world");
2634 /// # Ok::<_, rune::alloc::Error>(())
2635 /// ```
2636 #[inline]
2637 fn try_extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) -> Result<(), Error> {
2638 for value in iter {
2639 self.try_push_str(value)?;
2640 }
2641
2642 Ok(())
2643 }
2644}