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