non_empty_str/
string.rs

1//! Non-empty [`String`].
2
3#[cfg(not(any(feature = "std", feature = "alloc")))]
4compile_error!("expected either `std` or `alloc` to be enabled");
5
6#[cfg(feature = "std")]
7use std::{borrow::Cow, collections::TryReserveError};
8
9#[cfg(all(not(feature = "std"), feature = "alloc"))]
10use alloc::{
11    borrow::{Cow, ToOwned},
12    boxed::Box,
13    collections::TryReserveError,
14    string::{String, ToString},
15};
16
17use core::{
18    borrow::{Borrow, BorrowMut},
19    convert::Infallible,
20    fmt,
21    ops::{Add, AddAssign, Deref, DerefMut, RangeBounds},
22};
23
24use non_empty_iter::{FromNonEmptyIterator, IntoNonEmptyIterator, NonEmptyIterator};
25use non_empty_slice::{EmptyByteVec, EmptySlice, NonEmptyByteVec, NonEmptyBytes};
26use non_zero_size::Size;
27
28use thiserror::Error;
29
30use crate::{
31    boxed::{EmptyBoxedStr, NonEmptyBoxedStr},
32    cow::NonEmptyCowStr,
33    internal::{ByteVec, Bytes},
34    str::{EmptyStr, FromNonEmptyStr, NonEmptyStr, NonEmptyUtf8Error},
35};
36
37/// The error message used when the string is empty.
38pub const EMPTY_STRING: &str = "the string is empty";
39
40/// Similar to [`EmptyStr`], but holds the empty string provided.
41#[derive(Debug, Error)]
42#[error("{EMPTY_STRING}")]
43#[cfg_attr(
44    feature = "diagnostics",
45    derive(miette::Diagnostic),
46    diagnostic(code(non_empty_str::string), help("make sure the string is non-empty"))
47)]
48pub struct EmptyString {
49    string: String,
50}
51
52impl EmptyString {
53    // NOTE: this is private to prevent creating this error with non-empty strings
54    pub(crate) const fn new(string: String) -> Self {
55        Self { string }
56    }
57
58    /// Returns the contained empty string.
59    #[must_use]
60    pub fn get(self) -> String {
61        self.string
62    }
63
64    /// Constructs [`Self`] from [`EmptyBoxedStr`].
65    #[must_use]
66    pub fn from_empty_boxed_str(empty: EmptyBoxedStr) -> Self {
67        Self::new(empty.get().into_string())
68    }
69
70    /// Converts [`Self`] into [`EmptyBoxedStr`].
71    #[must_use]
72    pub fn into_empty_boxed_str(self) -> EmptyBoxedStr {
73        EmptyBoxedStr::from_empty_string(self)
74    }
75}
76
77/// Couples [`NonEmptyUtf8Error`] with the [`NonEmptyByteVec`] that is invalid UTF-8.
78#[derive(Debug, Error)]
79#[error("{error}")]
80#[cfg_attr(
81    feature = "diagnostics",
82    derive(miette::Diagnostic),
83    diagnostic(
84        code(non_empty_str::string::utf8),
85        help("make sure the bytes are valid UTF-8")
86    )
87)]
88pub struct FromNonEmptyUtf8Error {
89    #[source]
90    #[cfg_attr(feature = "diagnostics", diagnostic_source)]
91    error: NonEmptyUtf8Error,
92    bytes: NonEmptyByteVec,
93}
94
95impl FromNonEmptyUtf8Error {
96    // NOTE: this is private to prevent creating this error with valid UTF-8 bytes
97    pub(crate) const fn new(error: NonEmptyUtf8Error, bytes: NonEmptyByteVec) -> Self {
98        Self { error, bytes }
99    }
100
101    /// Returns contained invalid UTF-8 bytes as [`NonEmptyBytes`].
102    #[must_use]
103    pub const fn as_non_empty_bytes(&self) -> &NonEmptyBytes {
104        self.bytes.as_non_empty_slice()
105    }
106
107    /// Returns the contained non-empty bytes.
108    #[must_use]
109    pub fn into_non_empty_bytes(self) -> NonEmptyByteVec {
110        self.bytes
111    }
112
113    /// Returns the underlying UTF-8 error.
114    #[must_use]
115    pub const fn non_empty_error(&self) -> NonEmptyUtf8Error {
116        self.error
117    }
118
119    /// Recovers the underlying UTF-8 error and the non-empty bytes.
120    ///
121    /// This is the same as returning [`non_empty_error`] and [`into_non_empty_bytes`].
122    ///
123    /// [`non_empty_error`]: Self::non_empty_error
124    /// [`into_non_empty_bytes`]: Self::into_non_empty_bytes
125    #[must_use]
126    pub fn recover(self) -> (NonEmptyUtf8Error, NonEmptyByteVec) {
127        (self.non_empty_error(), self.into_non_empty_bytes())
128    }
129}
130
131/// Represents errors returned when the provided byte vector is empty or invalid UTF-8.
132#[derive(Debug, Error)]
133#[error(transparent)]
134#[cfg_attr(
135    feature = "diagnostics",
136    derive(miette::Diagnostic),
137    diagnostic(transparent)
138)]
139pub enum FromMaybeEmptyUtf8Error {
140    /// The received byte vector is empty.
141    Empty(#[from] EmptyByteVec),
142    /// The received byte vector is non-empty, but invalid UTF-8.
143    Utf8(#[from] FromNonEmptyUtf8Error),
144}
145
146/// Represents non-empty [`String`] values.
147#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
148#[repr(transparent)]
149pub struct NonEmptyString {
150    inner: String,
151}
152
153impl Clone for NonEmptyString {
154    fn clone(&self) -> Self {
155        // SAFETY: the string is non-empty by construction
156        unsafe { Self::new_unchecked(self.as_string().clone()) }
157    }
158
159    fn clone_from(&mut self, source: &Self) {
160        // SAFETY: cloning from non-empty string can not make the string empty
161        unsafe {
162            self.as_mut_string().clone_from(source.as_string());
163        }
164    }
165}
166
167impl fmt::Write for NonEmptyString {
168    fn write_str(&mut self, string: &str) -> fmt::Result {
169        // SAFETY: writing to non-empty string can not make the string empty
170        unsafe { self.as_mut_string().write_str(string) }
171    }
172
173    fn write_char(&mut self, character: char) -> fmt::Result {
174        // SAFETY: writing to non-empty string can not make the string empty
175        unsafe { self.as_mut_string().write_char(character) }
176    }
177
178    fn write_fmt(&mut self, arguments: fmt::Arguments<'_>) -> fmt::Result {
179        // SAFETY: writing to non-empty string can not make the string empty
180        unsafe { self.as_mut_string().write_fmt(arguments) }
181    }
182}
183
184impl fmt::Display for NonEmptyString {
185    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
186        self.as_string().fmt(formatter)
187    }
188}
189
190impl FromNonEmptyStr for NonEmptyString {
191    type Error = Infallible;
192
193    fn from_non_empty_str(string: &NonEmptyStr) -> Result<Self, Self::Error> {
194        Ok(Self::from_non_empty_str(string))
195    }
196}
197
198impl Borrow<NonEmptyStr> for NonEmptyString {
199    fn borrow(&self) -> &NonEmptyStr {
200        self.as_non_empty_str()
201    }
202}
203
204impl BorrowMut<NonEmptyStr> for NonEmptyString {
205    fn borrow_mut(&mut self) -> &mut NonEmptyStr {
206        self.as_non_empty_mut_str()
207    }
208}
209
210impl Borrow<str> for NonEmptyString {
211    fn borrow(&self) -> &str {
212        self.as_str()
213    }
214}
215
216impl BorrowMut<str> for NonEmptyString {
217    fn borrow_mut(&mut self) -> &mut str {
218        self.as_mut_str()
219    }
220}
221
222impl TryFrom<String> for NonEmptyString {
223    type Error = EmptyString;
224
225    fn try_from(string: String) -> Result<Self, Self::Error> {
226        Self::new(string)
227    }
228}
229
230impl From<NonEmptyString> for String {
231    fn from(non_empty: NonEmptyString) -> Self {
232        non_empty.into_string()
233    }
234}
235
236impl From<&NonEmptyStr> for NonEmptyString {
237    fn from(non_empty: &NonEmptyStr) -> Self {
238        non_empty.to_non_empty_string()
239    }
240}
241
242impl From<&mut NonEmptyStr> for NonEmptyString {
243    fn from(non_empty: &mut NonEmptyStr) -> Self {
244        non_empty.to_non_empty_string()
245    }
246}
247
248impl TryFrom<&str> for NonEmptyString {
249    type Error = EmptyStr;
250
251    fn try_from(string: &str) -> Result<Self, Self::Error> {
252        let non_empty_string: &NonEmptyStr = string.try_into()?;
253
254        Ok(non_empty_string.into())
255    }
256}
257
258impl TryFrom<&mut str> for NonEmptyString {
259    type Error = EmptyStr;
260
261    fn try_from(string: &mut str) -> Result<Self, Self::Error> {
262        let non_empty_string: &mut NonEmptyStr = string.try_into()?;
263
264        Ok(non_empty_string.into())
265    }
266}
267
268impl From<char> for NonEmptyString {
269    fn from(character: char) -> Self {
270        Self::single(character)
271    }
272}
273
274impl AsRef<Self> for NonEmptyString {
275    fn as_ref(&self) -> &Self {
276        self
277    }
278}
279
280impl AsMut<Self> for NonEmptyString {
281    fn as_mut(&mut self) -> &mut Self {
282        self
283    }
284}
285
286impl AsRef<String> for NonEmptyString {
287    fn as_ref(&self) -> &String {
288        self.as_string()
289    }
290}
291
292impl AsRef<NonEmptyStr> for NonEmptyString {
293    fn as_ref(&self) -> &NonEmptyStr {
294        self.as_non_empty_str()
295    }
296}
297
298impl AsMut<NonEmptyStr> for NonEmptyString {
299    fn as_mut(&mut self) -> &mut NonEmptyStr {
300        self.as_non_empty_mut_str()
301    }
302}
303
304impl AsRef<str> for NonEmptyString {
305    fn as_ref(&self) -> &str {
306        self.as_str()
307    }
308}
309
310impl AsMut<str> for NonEmptyString {
311    fn as_mut(&mut self) -> &mut str {
312        self.as_mut_str()
313    }
314}
315
316impl AsRef<Bytes> for NonEmptyString {
317    fn as_ref(&self) -> &Bytes {
318        self.as_bytes()
319    }
320}
321
322impl Deref for NonEmptyString {
323    type Target = NonEmptyStr;
324
325    fn deref(&self) -> &Self::Target {
326        self.as_non_empty_str()
327    }
328}
329
330impl DerefMut for NonEmptyString {
331    fn deref_mut(&mut self) -> &mut Self::Target {
332        self.as_non_empty_mut_str()
333    }
334}
335
336impl Add<&str> for NonEmptyString {
337    type Output = Self;
338
339    fn add(mut self, string: &str) -> Self::Output {
340        self.push_str(string);
341
342        self
343    }
344}
345
346impl Add<&NonEmptyStr> for NonEmptyString {
347    type Output = Self;
348
349    fn add(mut self, non_empty: &NonEmptyStr) -> Self::Output {
350        self.extend_from(non_empty);
351
352        self
353    }
354}
355
356impl AddAssign<&str> for NonEmptyString {
357    fn add_assign(&mut self, string: &str) {
358        self.push_str(string);
359    }
360}
361
362impl AddAssign<&NonEmptyStr> for NonEmptyString {
363    fn add_assign(&mut self, non_empty: &NonEmptyStr) {
364        self.extend_from(non_empty);
365    }
366}
367
368impl<'s> Extend<&'s str> for NonEmptyString {
369    fn extend<I: IntoIterator<Item = &'s str>>(&mut self, iterable: I) {
370        // SAFETY: extending can not make the string empty
371        unsafe {
372            self.as_mut_string().extend(iterable);
373        }
374    }
375}
376
377impl<'s> Extend<&'s NonEmptyStr> for NonEmptyString {
378    fn extend<I: IntoIterator<Item = &'s NonEmptyStr>>(&mut self, iterable: I) {
379        self.extend(iterable.into_iter().map(NonEmptyStr::as_str));
380    }
381}
382
383impl<'c> Extend<&'c char> for NonEmptyString {
384    fn extend<I: IntoIterator<Item = &'c char>>(&mut self, iterable: I) {
385        // SAFETY: extending can not make the string empty
386        unsafe {
387            self.as_mut_string().extend(iterable);
388        }
389    }
390}
391
392impl Extend<Box<str>> for NonEmptyString {
393    fn extend<I: IntoIterator<Item = Box<str>>>(&mut self, iterable: I) {
394        // SAFETY: extending can not make the string empty
395        unsafe {
396            self.as_mut_string().extend(iterable);
397        }
398    }
399}
400
401impl Extend<NonEmptyBoxedStr> for NonEmptyString {
402    fn extend<I: IntoIterator<Item = NonEmptyBoxedStr>>(&mut self, iterable: I) {
403        self.extend(iterable.into_iter().map(NonEmptyStr::into_boxed_str));
404    }
405}
406
407impl<'s> Extend<Cow<'s, str>> for NonEmptyString {
408    fn extend<I: IntoIterator<Item = Cow<'s, str>>>(&mut self, iterable: I) {
409        // SAFETY: extending can not make the string empty
410        unsafe {
411            self.as_mut_string().extend(iterable);
412        }
413    }
414}
415
416impl<'s> Extend<NonEmptyCowStr<'s>> for NonEmptyString {
417    fn extend<I: IntoIterator<Item = Cow<'s, NonEmptyStr>>>(&mut self, iterable: I) {
418        self.extend(iterable.into_iter().map(|non_empty| match non_empty {
419            Cow::Borrowed(string) => Cow::Borrowed(string.as_str()),
420            Cow::Owned(string) => Cow::Owned(string.into_string()),
421        }));
422    }
423}
424
425impl Extend<String> for NonEmptyString {
426    fn extend<I: IntoIterator<Item = String>>(&mut self, iterable: I) {
427        // SAFETY: extending can not make the string empty
428        unsafe {
429            self.as_mut_string().extend(iterable);
430        }
431    }
432}
433
434impl Extend<Self> for NonEmptyString {
435    fn extend<I: IntoIterator<Item = Self>>(&mut self, iterable: I) {
436        self.extend(iterable.into_iter().map(Self::into_string));
437    }
438}
439
440impl Extend<char> for NonEmptyString {
441    fn extend<I: IntoIterator<Item = char>>(&mut self, iterable: I) {
442        // SAFETY: extending can not make the string empty
443        unsafe {
444            self.as_mut_string().extend(iterable);
445        }
446    }
447}
448
449impl NonEmptyString {
450    /// Constructs [`Self`], provided that the [`String`] is non-empty.
451    ///
452    /// # Errors
453    ///
454    /// Returns [`EmptyString`] if the string is empty.
455    ///
456    /// # Examples
457    ///
458    /// Basic snippet:
459    ///
460    /// ```
461    /// use non_empty_str::NonEmptyString;
462    ///
463    /// let message = NonEmptyString::new("Hello, world!".to_owned()).unwrap();
464    /// ```
465    ///
466    /// Handling possible errors and recovering empty strings:
467    ///
468    /// ```
469    /// use non_empty_str::NonEmptyString;
470    ///
471    /// let empty_owned = NonEmptyString::new(String::new()).unwrap_err();
472    ///
473    /// let empty = empty_owned.get();
474    /// ```
475    pub const fn new(string: String) -> Result<Self, EmptyString> {
476        if string.is_empty() {
477            return Err(EmptyString::new(string));
478        }
479
480        // SAFETY: the string is non-empty at this point
481        Ok(unsafe { Self::new_unchecked(string) })
482    }
483
484    /// Constructs [`Self`] without checking if the string is non-empty.
485    ///
486    /// # Safety
487    ///
488    /// The caller must ensure that the string is non-empty.
489    #[must_use]
490    pub const unsafe fn new_unchecked(inner: String) -> Self {
491        debug_assert!(!inner.is_empty());
492
493        Self { inner }
494    }
495
496    #[cfg(feature = "unsafe-assert")]
497    const fn assert_non_empty(&self) {
498        use core::hint::assert_unchecked;
499
500        // SAFETY: the string is non-empty by construction
501        unsafe {
502            assert_unchecked(!self.as_string_no_assert().is_empty());
503        }
504    }
505
506    const fn as_string_no_assert(&self) -> &String {
507        &self.inner
508    }
509
510    const unsafe fn as_mut_string_no_assert(&mut self) -> &mut String {
511        &mut self.inner
512    }
513
514    fn into_string_no_assert(self) -> String {
515        self.inner
516    }
517
518    /// Constructs [`Self`] from [`NonEmptyStr`] via cloning.
519    ///
520    /// # Examples
521    ///
522    /// Basic snippet:
523    ///
524    /// ```
525    /// use non_empty_str::{NonEmptyString, NonEmptyStr};
526    ///
527    /// let nekit = NonEmptyStr::from_str("nekit").unwrap();
528    ///
529    /// let owned = NonEmptyString::from_non_empty_str(nekit);
530    /// ```
531    #[must_use]
532    pub fn from_non_empty_str(string: &NonEmptyStr) -> Self {
533        // SAFETY: the string is non-empty by construction
534        unsafe { Self::new_unchecked(string.as_str().to_owned()) }
535    }
536
537    /// Checks if the string is empty. Always returns [`false`].
538    ///
539    /// This method is deprecated since the string is never empty.
540    #[deprecated = "this string is never empty"]
541    #[must_use]
542    pub const fn is_empty(&self) -> bool {
543        false
544    }
545
546    /// Returns the length of the string in bytes as [`Size`].
547    #[must_use]
548    pub const fn len(&self) -> Size {
549        let len = self.as_string().len();
550
551        // SAFETY: the string is non-empty by construction, so its length is non-zero
552        unsafe { Size::new_unchecked(len) }
553    }
554
555    /// Returns the capacity of the string in bytes as [`Size`].
556    #[must_use]
557    pub const fn capacity(&self) -> Size {
558        let capacity = self.as_string().capacity();
559
560        // SAFETY: capacity is always non-zero for non-empty strings
561        unsafe { Size::new_unchecked(capacity) }
562    }
563
564    /// Extracts the string slice containing the entire string.
565    #[must_use]
566    pub const fn as_str(&self) -> &str {
567        self.as_string().as_str()
568    }
569
570    /// Returns the mutable string slice containing the entire string.
571    pub const fn as_mut_str(&mut self) -> &mut str {
572        // SAFETY: getting mutable slice can not make the string empty
573        unsafe { self.as_mut_string().as_mut_str() }
574    }
575
576    /// Returns contained string reference as [`NonEmptyStr`].
577    #[must_use]
578    pub const fn as_non_empty_str(&self) -> &NonEmptyStr {
579        // SAFETY: the string is non-empty by construction
580        unsafe { NonEmptyStr::from_str_unchecked(self.as_str()) }
581    }
582
583    /// Returns contained mutable string reference as [`NonEmptyStr`].
584    pub const fn as_non_empty_mut_str(&mut self) -> &mut NonEmptyStr {
585        // SAFETY: the string is non-empty by construction
586        unsafe { NonEmptyStr::from_mut_str_unchecked(self.as_mut_str()) }
587    }
588
589    /// Returns the underlying bytes of the string.
590    #[must_use]
591    pub const fn as_bytes(&self) -> &Bytes {
592        self.as_str().as_bytes()
593    }
594
595    /// Returns the underlying mutable bytes of the string.
596    ///
597    /// # Safety
598    ///
599    /// The caller must ensure that the bytes remain valid UTF-8.
600    pub const unsafe fn as_bytes_mut(&mut self) -> &mut Bytes {
601        // SAFETY: getting mutable bytes can not make the string empty
602        // moreover, the caller must ensure that the bytes remain valid UTF-8
603        unsafe { self.as_mut_str().as_bytes_mut() }
604    }
605
606    /// Returns the underlying bytes of the string as [`NonEmptyBytes`].
607    #[must_use]
608    pub const fn as_non_empty_bytes(&self) -> &NonEmptyBytes {
609        self.as_non_empty_str().as_non_empty_bytes()
610    }
611
612    /// Returns the underlying mutable bytes of the string as [`NonEmptyBytes`].
613    ///
614    /// # Safety
615    ///
616    /// The caller must ensure that the bytes remain valid UTF-8.
617    pub const unsafe fn as_non_empty_bytes_mut(&mut self) -> &mut NonEmptyBytes {
618        // SAFETY: the caller must ensure that the bytes remain valid UTF-8
619        unsafe { self.as_non_empty_mut_str().as_non_empty_bytes_mut() }
620    }
621
622    /// Returns the contained string reference.
623    #[must_use]
624    pub const fn as_string(&self) -> &String {
625        #[cfg(feature = "unsafe-assert")]
626        self.assert_non_empty();
627
628        self.as_string_no_assert()
629    }
630
631    /// Similar to [`from_non_empty_utf8_lossy`], but accepts the possibility of empty bytes.
632    ///
633    /// # Errors
634    ///
635    /// Returns [`EmptySlice`] if the given bytes are empty.
636    ///
637    /// [`from_non_empty_utf8_lossy`]: Self::from_non_empty_utf8_lossy
638    pub fn from_utf8_lossy(bytes: &Bytes) -> Result<NonEmptyCowStr<'_>, EmptySlice> {
639        NonEmptyBytes::try_from_slice(bytes).map(Self::from_non_empty_utf8_lossy)
640    }
641
642    /// Similar to [`from_non_empty_utf8_lossy_owned`], but
643    /// accepts the possibility of empty byte vectors.
644    ///
645    /// # Errors
646    ///
647    /// Returns [`EmptyByteVec`] if the given byte vector is empty.
648    ///
649    /// [`from_non_empty_utf8_lossy_owned`]: Self::from_non_empty_utf8_lossy_owned
650    pub fn from_utf8_lossy_owned(bytes: ByteVec) -> Result<Self, EmptyByteVec> {
651        NonEmptyByteVec::new(bytes).map(Self::from_non_empty_utf8_lossy_owned)
652    }
653
654    /// Converts the given [`NonEmptyBytes`] to non-empty string, including invalid characters.
655    ///
656    /// Any invalid UTF-8 sequences will be replaced with [`char::REPLACEMENT_CHARACTER`].
657    ///
658    /// This function returns [`NonEmptyCowStr<'_>`], since it may borrow the input bytes
659    /// in case they are valid UTF-8, or allocate new non-empty string otherwise.
660    #[must_use]
661    pub fn from_non_empty_utf8_lossy(non_empty: &NonEmptyBytes) -> NonEmptyCowStr<'_> {
662        match String::from_utf8_lossy(non_empty.as_slice()) {
663            // SAFETY: passing non-empty bytes results in non-empty lossy string
664            Cow::Owned(string) => Cow::Owned(unsafe { Self::new_unchecked(string) }),
665            Cow::Borrowed(string) => {
666                // SAFETY: bytes are valid and non-empty, so this is safe
667                Cow::Borrowed(unsafe { NonEmptyStr::from_str_unchecked(string) })
668            }
669        }
670    }
671
672    /// Converts the given [`NonEmptyByteVec`] to non-empty string, including invalid characters.
673    ///
674    /// Any invalid UTF-8 sequences will be replaced with [`char::REPLACEMENT_CHARACTER`].
675    ///
676    /// This function does not guarantee reuse of the original byte vector allocation.
677    #[must_use]
678    pub fn from_non_empty_utf8_lossy_owned(non_empty: NonEmptyByteVec) -> Self {
679        let cow = Self::from_non_empty_utf8_lossy(non_empty.as_non_empty_slice());
680
681        if let Cow::Owned(string) = cow {
682            string
683        } else {
684            // SAFETY: if `from_non_empty_utf8_lossy` returns `Cow::Borrowed`, it is valid UTF-8
685            // moreover, the bytes are non-empty by construction, so this is safe
686            unsafe { Self::from_non_empty_utf8_unchecked(non_empty) }
687        }
688    }
689
690    /// Converts the given byte vector to non-empty string if it is non-empty and valid UTF-8.
691    ///
692    /// # Errors
693    ///
694    /// Returns [`FromMaybeEmptyUtf8Error`] if the byte vector is empty or invalid UTF-8.
695    pub fn from_utf8(bytes: ByteVec) -> Result<Self, FromMaybeEmptyUtf8Error> {
696        let non_empty = NonEmptyByteVec::new(bytes)?;
697
698        let string = Self::from_non_empty_utf8(non_empty)?;
699
700        Ok(string)
701    }
702
703    /// Converts the given [`NonEmptyByteVec`] to non-empty string if it is valid UTF-8.
704    ///
705    /// # Errors
706    ///
707    /// Returns [`FromNonEmptyUtf8Error`] if the byte vector is invalid UTF-8.
708    pub fn from_non_empty_utf8(non_empty: NonEmptyByteVec) -> Result<Self, FromNonEmptyUtf8Error> {
709        let string = String::from_utf8(non_empty.into_vec()).map_err(|error| {
710            let non_empty_error = error.utf8_error().into();
711
712            // SAFETY: reclaiming ownership of previously passed non-empty bytes is safe
713            let non_empty = unsafe { NonEmptyByteVec::new_unchecked(error.into_bytes()) };
714
715            FromNonEmptyUtf8Error::new(non_empty_error, non_empty)
716        })?;
717
718        // SAFETY: the bytes are non-empty by construction, so is the resulting string
719        Ok(unsafe { Self::new_unchecked(string) })
720    }
721
722    /// Constructs [`Self`] from the given [`NonEmptyByteVec`] without checking for UTF-8 validity.
723    ///
724    /// # Safety
725    ///
726    /// The caller must ensure that the non-empty byte vector is valid UTF-8.
727    #[must_use]
728    pub unsafe fn from_non_empty_utf8_unchecked(non_empty: NonEmptyByteVec) -> Self {
729        // SAFETY: the caller must ensure that the bytes are valid UTF-8
730        // moreover, the bytes are non-empty by construction, so is the resulting string
731        unsafe { Self::from_utf8_unchecked(non_empty.into_vec()) }
732    }
733
734    /// Constructs [`Self`] from the given byte vector without
735    /// checking for emptiness or UTF-8 validity.
736    ///
737    /// # Safety
738    ///
739    /// The caller must ensure that the byte vector is non-empty and valid UTF-8.
740    #[must_use]
741    pub unsafe fn from_utf8_unchecked(bytes: ByteVec) -> Self {
742        // SAFETY: the caller must ensure that the bytes are non-empty and valid UTF-8
743        unsafe { Self::new_unchecked(String::from_utf8_unchecked(bytes)) }
744    }
745
746    /// Returns the contained mutable string reference.
747    ///
748    /// # Safety
749    ///
750    /// The caller must ensure that the string remains non-empty.
751    #[must_use]
752    pub const unsafe fn as_mut_string(&mut self) -> &mut String {
753        #[cfg(feature = "unsafe-assert")]
754        self.assert_non_empty();
755
756        // SAFETY: the caller must ensure that the string remains non-empty
757        unsafe { self.as_mut_string_no_assert() }
758    }
759
760    /// Returns the contained [`String`].
761    #[must_use]
762    pub fn into_string(self) -> String {
763        #[cfg(feature = "unsafe-assert")]
764        self.assert_non_empty();
765
766        self.into_string_no_assert()
767    }
768
769    /// Converts [`Self`] into the underlying byte vector.
770    #[must_use]
771    pub fn into_bytes(self) -> ByteVec {
772        self.into_string().into_bytes()
773    }
774
775    /// Converts [`Self`] into the underlying byte vector as [`NonEmptyByteVec`].
776    #[must_use]
777    pub fn into_non_empty_bytes(self) -> NonEmptyByteVec {
778        // SAFETY: the string is non-empty by construction, so are its bytes
779        unsafe { NonEmptyByteVec::new_unchecked(self.into_bytes()) }
780    }
781
782    /// Appends the given [`char`] to the end of this string.
783    pub fn push(&mut self, character: char) {
784        // SAFETY: pushing can not make the string empty
785        unsafe {
786            self.as_mut_string().push(character);
787        }
788    }
789
790    /// Appends the given [`str`] onto the end of this string.
791    pub fn push_str(&mut self, string: &str) {
792        // SAFETY: pushing can not make the string empty
793        unsafe {
794            self.as_mut_string().push_str(string);
795        }
796    }
797
798    /// Copies bytes from the given range to the end of the string.
799    ///
800    /// # Panics
801    ///
802    /// Panics if the range is out of bounds or not on character boundaries.
803    pub fn extend_from_within<R: RangeBounds<usize>>(&mut self, source: R) {
804        // SAFETY: extending can not make the string empty
805        unsafe {
806            self.as_mut_string().extend_from_within(source);
807        }
808    }
809
810    /// Appends anything that can be converted to string onto the end of this string.
811    pub fn extend_from<S: AsRef<str>>(&mut self, string: S) {
812        self.push_str(string.as_ref());
813    }
814
815    /// Reserves capacity for at least `additional` more bytes to be added.
816    ///
817    /// Note that the additional capacity is required to be non-zero via [`Size`].
818    ///
819    /// This method can over-allocate to speculatively avoid frequent reallocations.
820    ///
821    /// Does nothing if the capacity is already sufficient.
822    ///
823    /// # Panics
824    ///
825    /// Panics on capacity overflow.
826    pub fn reserve(&mut self, additional: Size) {
827        // SAFETY: reserving can not make the string empty
828        unsafe {
829            self.as_mut_string().reserve(additional.get());
830        }
831    }
832
833    /// Reserves the minimum capacity for exactly `additional` more values to be added.
834    ///
835    /// Note that the additional capacity is required to be non-zero via [`Size`].
836    ///
837    /// Unlike [`reserve`], this method will not deliberately over-allocate
838    /// to speculatively avoid frequent reallocations.
839    ///
840    /// Does nothing if the capacity is already sufficient.
841    ///
842    /// # Panics
843    ///
844    /// Panics on capacity overflow.
845    ///
846    /// [`reserve`]: Self::reserve
847    pub fn reserve_exact(&mut self, additional: Size) {
848        // SAFETY: reserving can not make the string empty
849        unsafe {
850            self.as_mut_string().reserve_exact(additional.get());
851        }
852    }
853
854    /// Tries to reserve capacity for at least `additional` more bytes to be added.
855    ///
856    /// Note that the additional capacity is required to be non-zero via [`Size`].
857    ///
858    /// This method can over-allocate to speculatively avoid frequent reallocations.
859    ///
860    /// Does nothing if the capacity is already sufficient.
861    ///
862    /// # Errors
863    ///
864    /// Returns [`TryReserveError`] if the allocation fails or capacity overflows.
865    pub fn try_reserve(&mut self, additional: Size) -> Result<(), TryReserveError> {
866        // SAFETY: reserving can not make the string empty
867        unsafe { self.as_mut_string().try_reserve(additional.get()) }
868    }
869
870    /// Tries to reserve the minimum capacity for exactly `additional` more bytes to be added.
871    ///
872    /// Note that the additional capacity is required to be non-zero via [`Size`].
873    ///
874    /// Unlike [`try_reserve`], this method will not deliberately over-allocate
875    /// to speculatively avoid frequent reallocations.
876    ///
877    /// Does nothing if the capacity is already sufficient.
878    ///
879    /// # Errors
880    ///
881    /// Returns [`TryReserveError`] if the allocation fails or capacity overflows.
882    ///
883    /// [`try_reserve`]: Self::try_reserve
884    pub fn try_reserve_exact(&mut self, additional: Size) -> Result<(), TryReserveError> {
885        // SAFETY: reserving can not make the string empty
886        unsafe { self.as_mut_string().try_reserve_exact(additional.get()) }
887    }
888
889    /// Shrinks the capacity of the string as much as possible.
890    pub fn shrink_to_fit(&mut self) {
891        // SAFETY: shrinking can not make the string empty
892        unsafe {
893            self.as_mut_string().shrink_to_fit();
894        }
895    }
896
897    /// Shrinks the capacity of the string to the specified amount.
898    ///
899    /// The capacity will remain at least as large as both the length and the supplied amount.
900    ///
901    /// Does nothing if the current capacity is less than or equal to the specified amount.
902    pub fn shrink_to(&mut self, capacity: Size) {
903        // SAFETY: shrinking can not make the string empty
904        unsafe {
905            self.as_mut_string().shrink_to(capacity.get());
906        }
907    }
908
909    /// Shortens this string to the specified non-zero length.
910    ///
911    /// Does nothing if `new` is greater than or equal to the string's [`len`].
912    ///
913    /// [`len`]: Self::len
914    pub fn truncate(&mut self, new: Size) {
915        // SAFETY: truncating to non-zero length can not make the string empty
916        unsafe {
917            self.as_mut_string().truncate(new.get());
918        }
919    }
920
921    /// Checks whether the string is almost empty, meaning it only contains one character.
922    #[must_use]
923    pub fn next_empty(&self) -> bool {
924        let (character, _) = self.chars().consume();
925
926        self.len().get() - character.len_utf8() == 0
927    }
928
929    /// The negated version of [`next_empty`].
930    ///
931    /// [`next_empty`]: Self::next_empty
932    #[must_use]
933    pub fn next_non_empty(&self) -> bool {
934        !self.next_empty()
935    }
936
937    /// Removes the last character from the string and returns it,
938    /// or [`None`] if the string would become empty.
939    pub fn pop(&mut self) -> Option<char> {
940        self.next_non_empty()
941            // SAFETY: popping only when the string would remain non-empty
942            .then(|| unsafe { self.as_mut_string().pop() })
943            .flatten()
944    }
945
946    /// Consumes and leaks the string, returning the mutable reference of its contents.
947    #[must_use]
948    pub fn leak<'a>(self) -> &'a mut str {
949        self.into_string().leak()
950    }
951
952    /// Similar to [`leak`], but returns [`NonEmptyStr`].
953    ///
954    /// [`leak`]: Self::leak
955    #[must_use]
956    pub fn leak_non_empty<'a>(self) -> &'a mut NonEmptyStr {
957        // SAFETY: the string is non-empty by construction, so is the leaked string
958        unsafe { NonEmptyStr::from_mut_str_unchecked(self.leak()) }
959    }
960
961    /// Inserts the given character at the specified index,
962    /// shifting all bytes after it to the right.
963    ///
964    /// # Panics
965    ///
966    /// Panics if the index is out of bounds or not on character boundary.
967    pub fn insert(&mut self, index: usize, character: char) {
968        // SAFETY: inserting can not make the string empty
969        unsafe {
970            self.as_mut_string().insert(index, character);
971        }
972    }
973
974    /// Inserts the given string at the specified index, shifting all bytes after it to the right.
975    ///
976    /// # Panics
977    ///
978    /// Panics if the index is out of bounds or not on character boundary.
979    pub fn insert_str(&mut self, index: usize, string: &str) {
980        // SAFETY: inserting can not make the string empty
981        unsafe {
982            self.as_mut_string().insert_str(index, string);
983        }
984    }
985
986    /// Inserts anything that can be converted to string at the specified index,
987    /// shifting all bytes after it to the right.
988    ///
989    /// # Panics
990    ///
991    /// Panics if the index is out of bounds or not on character boundary.
992    pub fn insert_from<S: AsRef<str>>(&mut self, index: usize, string: S) {
993        self.insert_str(index, string.as_ref());
994    }
995
996    /// Removes and returns the character at the given index within the string,
997    /// shifting all bytes after it to the left.
998    ///
999    /// Returns [`None`] if the string would become empty.
1000    ///
1001    /// # Panics
1002    ///
1003    /// Panics if the index is out of bounds or not on character boundary.
1004    pub fn remove(&mut self, index: usize) -> Option<char> {
1005        self.next_non_empty()
1006            // SAFETY: removing only when the string would remain non-empty
1007            .then(|| unsafe { self.as_mut_string().remove(index) })
1008    }
1009
1010    /// Splits the string into two at the given non-zero index.
1011    ///
1012    /// The index has to be non-zero to guaratee that the string would remain non-empty.
1013    ///
1014    /// # Panics
1015    ///
1016    /// Panics if the provided index is out of bounds or not on character boundary.
1017    pub fn split_off(&mut self, at: Size) -> String {
1018        // SAFETY: splitting at non-zero index can not make the string empty
1019        unsafe { self.as_mut_string().split_off(at.get()) }
1020    }
1021}
1022
1023impl ToOwned for NonEmptyStr {
1024    type Owned = NonEmptyString;
1025
1026    fn to_owned(&self) -> Self::Owned {
1027        self.to_non_empty_string()
1028    }
1029}
1030
1031impl NonEmptyStr {
1032    /// Converts [`Self`] to [`NonEmptyString`] via cloning.
1033    #[must_use]
1034    pub fn to_non_empty_string(&self) -> NonEmptyString {
1035        NonEmptyString::from_non_empty_str(self)
1036    }
1037
1038    /// Converts [`Self`] to [`NonEmptyByteVec`] via cloning.
1039    #[must_use]
1040    pub fn to_non_empty_bytes(&self) -> NonEmptyByteVec {
1041        self.to_non_empty_string().into_non_empty_bytes()
1042    }
1043
1044    /// Converts this string to its lowercase equivalent.
1045    #[must_use]
1046    pub fn to_lowercase(&self) -> String {
1047        self.as_str().to_lowercase()
1048    }
1049
1050    /// Converts this string to its uppercase equivalent.
1051    #[must_use]
1052    pub fn to_uppercase(&self) -> String {
1053        self.as_str().to_uppercase()
1054    }
1055
1056    /// Creates [`NonEmptyString`] by repeating this string certain number of times.
1057    ///
1058    /// Note that the count is non-zero in order to guarantee that
1059    /// the resulting string is non-empty.
1060    ///
1061    /// # Panics
1062    ///
1063    /// Panics on capacity overflow.
1064    #[must_use]
1065    pub fn repeat(&self, count: Size) -> NonEmptyString {
1066        let non_empty = self.as_str().repeat(count.get());
1067
1068        // SAFETY: repeating non-empty string non-zero times results in non-empty string
1069        unsafe { NonEmptyString::new_unchecked(non_empty) }
1070    }
1071
1072    /// Converts this string to its lowercase equivalent as [`NonEmptyString`].
1073    #[must_use]
1074    pub fn to_non_empty_lowercase(&self) -> NonEmptyString {
1075        // SAFETY: converting non-empty string to lowercase gives non-empty output
1076        unsafe { NonEmptyString::new_unchecked(self.to_lowercase()) }
1077    }
1078
1079    /// Converts this string to its uppercase equivalent as [`NonEmptyString`].
1080    #[must_use]
1081    pub fn to_non_empty_uppercase(&self) -> NonEmptyString {
1082        // SAFETY: converting non-empty string to uppercase gives non-empty output
1083        unsafe { NonEmptyString::new_unchecked(self.to_uppercase()) }
1084    }
1085}
1086
1087impl NonEmptyString {
1088    /// Constructs [`Self`] containing single provided character.
1089    #[must_use]
1090    pub fn single(character: char) -> Self {
1091        // SAFETY: non-empty construction
1092        unsafe { Self::new_unchecked(character.to_string()) }
1093    }
1094
1095    /// Constructs [`Self`] with the specified capacity in bytes, pushing the provided character.
1096    #[must_use]
1097    pub fn with_capacity_and_char(capacity: Size, character: char) -> Self {
1098        let mut string = String::with_capacity(capacity.get());
1099
1100        string.push(character);
1101
1102        // SAFETY: non-empty construction
1103        unsafe { Self::new_unchecked(string) }
1104    }
1105}
1106
1107impl FromNonEmptyIterator<char> for NonEmptyString {
1108    fn from_non_empty_iter<I: IntoNonEmptyIterator<Item = char>>(iterable: I) -> Self {
1109        let (character, iterator) = iterable.into_non_empty_iter().consume();
1110
1111        let mut output = Self::single(character);
1112
1113        output.extend(iterator);
1114
1115        output
1116    }
1117}
1118
1119impl<'c> FromNonEmptyIterator<&'c char> for NonEmptyString {
1120    fn from_non_empty_iter<I: IntoNonEmptyIterator<Item = &'c char>>(iterable: I) -> Self {
1121        let (&character, iterator) = iterable.into_non_empty_iter().consume();
1122
1123        let mut output = Self::single(character);
1124
1125        output.extend(iterator);
1126
1127        output
1128    }
1129}
1130
1131impl<'s> FromNonEmptyIterator<&'s NonEmptyStr> for NonEmptyString {
1132    fn from_non_empty_iter<I: IntoNonEmptyIterator<Item = &'s NonEmptyStr>>(iterable: I) -> Self {
1133        let (non_empty, iterator) = iterable.into_non_empty_iter().consume();
1134
1135        let mut output = Self::from_non_empty_str(non_empty);
1136
1137        output.extend(iterator);
1138
1139        output
1140    }
1141}
1142
1143impl FromNonEmptyIterator<Self> for NonEmptyString {
1144    fn from_non_empty_iter<I: IntoNonEmptyIterator<Item = Self>>(iterable: I) -> Self {
1145        let (mut output, iterator) = iterable.into_non_empty_iter().consume();
1146
1147        output.extend(iterator);
1148
1149        output
1150    }
1151}
1152
1153impl FromNonEmptyIterator<NonEmptyBoxedStr> for NonEmptyString {
1154    fn from_non_empty_iter<I: IntoNonEmptyIterator<Item = NonEmptyBoxedStr>>(iterable: I) -> Self {
1155        let (non_empty, iterator) = iterable.into_non_empty_iter().consume();
1156
1157        let mut output = Self::from_non_empty_boxed_str(non_empty);
1158
1159        output.extend(iterator);
1160
1161        output
1162    }
1163}
1164
1165impl<'s> FromNonEmptyIterator<NonEmptyCowStr<'s>> for NonEmptyString {
1166    fn from_non_empty_iter<I: IntoNonEmptyIterator<Item = NonEmptyCowStr<'s>>>(
1167        iterable: I,
1168    ) -> Self {
1169        let (non_empty, iterator) = iterable.into_non_empty_iter().consume();
1170
1171        let mut output = non_empty.into_owned();
1172
1173        output.extend(iterator);
1174
1175        output
1176    }
1177}