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