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    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
331impl Deref for NonEmptyString {
332    type Target = NonEmptyStr;
333
334    fn deref(&self) -> &Self::Target {
335        self.as_non_empty_str()
336    }
337}
338
339impl DerefMut for NonEmptyString {
340    fn deref_mut(&mut self) -> &mut Self::Target {
341        self.as_non_empty_mut_str()
342    }
343}
344
345impl Add<&str> for NonEmptyString {
346    type Output = Self;
347
348    fn add(mut self, string: &str) -> Self::Output {
349        self.push_str(string);
350
351        self
352    }
353}
354
355impl Add<&NonEmptyStr> for NonEmptyString {
356    type Output = Self;
357
358    fn add(mut self, non_empty: &NonEmptyStr) -> Self::Output {
359        self.extend_from(non_empty);
360
361        self
362    }
363}
364
365impl AddAssign<&str> for NonEmptyString {
366    fn add_assign(&mut self, string: &str) {
367        self.push_str(string);
368    }
369}
370
371impl AddAssign<&NonEmptyStr> for NonEmptyString {
372    fn add_assign(&mut self, non_empty: &NonEmptyStr) {
373        self.extend_from(non_empty);
374    }
375}
376
377impl<'s> Extend<&'s str> for NonEmptyString {
378    fn extend<I: IntoIterator<Item = &'s str>>(&mut self, iterable: I) {
379        // SAFETY: extending can not make the string empty
380        unsafe {
381            self.as_mut_string().extend(iterable);
382        }
383    }
384}
385
386impl<'s> Extend<&'s NonEmptyStr> for NonEmptyString {
387    fn extend<I: IntoIterator<Item = &'s NonEmptyStr>>(&mut self, iterable: I) {
388        self.extend(iterable.into_iter().map(NonEmptyStr::as_str));
389    }
390}
391
392impl<'c> Extend<&'c char> for NonEmptyString {
393    fn extend<I: IntoIterator<Item = &'c char>>(&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<Box<str>> for NonEmptyString {
402    fn extend<I: IntoIterator<Item = Box<str>>>(&mut self, iterable: I) {
403        // SAFETY: extending can not make the string empty
404        unsafe {
405            self.as_mut_string().extend(iterable);
406        }
407    }
408}
409
410impl Extend<NonEmptyBoxedStr> for NonEmptyString {
411    fn extend<I: IntoIterator<Item = NonEmptyBoxedStr>>(&mut self, iterable: I) {
412        self.extend(iterable.into_iter().map(NonEmptyStr::into_boxed_str));
413    }
414}
415
416impl<'s> Extend<Cow<'s, str>> for NonEmptyString {
417    fn extend<I: IntoIterator<Item = Cow<'s, str>>>(&mut self, iterable: I) {
418        // SAFETY: extending can not make the string empty
419        unsafe {
420            self.as_mut_string().extend(iterable);
421        }
422    }
423}
424
425impl<'s> Extend<NonEmptyCowStr<'s>> for NonEmptyString {
426    fn extend<I: IntoIterator<Item = Cow<'s, NonEmptyStr>>>(&mut self, iterable: I) {
427        self.extend(iterable.into_iter().map(|non_empty| match non_empty {
428            Cow::Borrowed(string) => Cow::Borrowed(string.as_str()),
429            Cow::Owned(string) => Cow::Owned(string.into_string()),
430        }));
431    }
432}
433
434impl Extend<String> for NonEmptyString {
435    fn extend<I: IntoIterator<Item = String>>(&mut self, iterable: I) {
436        // SAFETY: extending can not make the string empty
437        unsafe {
438            self.as_mut_string().extend(iterable);
439        }
440    }
441}
442
443impl Extend<Self> for NonEmptyString {
444    fn extend<I: IntoIterator<Item = Self>>(&mut self, iterable: I) {
445        self.extend(iterable.into_iter().map(Self::into_string));
446    }
447}
448
449impl Extend<char> for NonEmptyString {
450    fn extend<I: IntoIterator<Item = char>>(&mut self, iterable: I) {
451        // SAFETY: extending can not make the string empty
452        unsafe {
453            self.as_mut_string().extend(iterable);
454        }
455    }
456}
457
458impl NonEmptyString {
459    /// Constructs [`Self`], provided that the [`String`] is non-empty.
460    ///
461    /// # Errors
462    ///
463    /// Returns [`EmptyString`] if the string is empty.
464    ///
465    /// # Examples
466    ///
467    /// Basic snippet:
468    ///
469    /// ```
470    /// use non_empty_str::NonEmptyString;
471    ///
472    /// let message = NonEmptyString::new("Hello, world!".to_owned()).unwrap();
473    /// ```
474    ///
475    /// Handling possible errors and recovering empty strings:
476    ///
477    /// ```
478    /// use non_empty_str::NonEmptyString;
479    ///
480    /// let empty_owned = NonEmptyString::new(String::new()).unwrap_err();
481    ///
482    /// let empty = empty_owned.get();
483    /// ```
484    pub const fn new(string: String) -> Result<Self, EmptyString> {
485        if string.is_empty() {
486            return Err(EmptyString::new(string));
487        }
488
489        // SAFETY: the string is non-empty at this point
490        Ok(unsafe { Self::new_unchecked(string) })
491    }
492
493    /// Constructs [`Self`] without checking if the string is non-empty.
494    ///
495    /// # Safety
496    ///
497    /// The caller must ensure that the string is non-empty.
498    #[must_use]
499    pub const unsafe fn new_unchecked(inner: String) -> Self {
500        debug_assert!(!inner.is_empty());
501
502        Self { inner }
503    }
504
505    #[cfg(feature = "unsafe-assert")]
506    const fn assert_non_empty(&self) {
507        use core::hint::assert_unchecked;
508
509        // SAFETY: the string is non-empty by construction
510        unsafe {
511            assert_unchecked(!self.as_string_no_assert().is_empty());
512        }
513    }
514
515    const fn as_string_no_assert(&self) -> &String {
516        &self.inner
517    }
518
519    const unsafe fn as_mut_string_no_assert(&mut self) -> &mut String {
520        &mut self.inner
521    }
522
523    fn into_string_no_assert(self) -> String {
524        self.inner
525    }
526
527    /// Constructs [`Self`] from [`NonEmptyStr`] via cloning.
528    ///
529    /// # Examples
530    ///
531    /// Basic snippet:
532    ///
533    /// ```
534    /// use non_empty_str::{NonEmptyString, NonEmptyStr};
535    ///
536    /// let nekit = NonEmptyStr::from_str("nekit").unwrap();
537    ///
538    /// let owned = NonEmptyString::from_non_empty_str(nekit);
539    /// ```
540    #[must_use]
541    pub fn from_non_empty_str(string: &NonEmptyStr) -> Self {
542        // SAFETY: the string is non-empty by construction
543        unsafe { Self::new_unchecked(string.as_str().to_owned()) }
544    }
545
546    /// Checks if the string is empty. Always returns [`false`].
547    ///
548    /// This method is deprecated since the string is never empty.
549    #[deprecated = "this string is never empty"]
550    #[must_use]
551    pub const fn is_empty(&self) -> bool {
552        false
553    }
554
555    /// Returns the length of the string in bytes as [`Size`].
556    #[must_use]
557    pub const fn len(&self) -> Size {
558        let len = self.as_string().len();
559
560        // SAFETY: the string is non-empty by construction, so its length is non-zero
561        unsafe { Size::new_unchecked(len) }
562    }
563
564    /// Returns the capacity of the string in bytes as [`Size`].
565    #[must_use]
566    pub const fn capacity(&self) -> Size {
567        let capacity = self.as_string().capacity();
568
569        // SAFETY: capacity is always non-zero for non-empty strings
570        unsafe { Size::new_unchecked(capacity) }
571    }
572
573    /// Extracts the string slice containing the entire string.
574    #[must_use]
575    pub const fn as_str(&self) -> &str {
576        self.as_string().as_str()
577    }
578
579    /// Returns the mutable string slice containing the entire string.
580    pub const fn as_mut_str(&mut self) -> &mut str {
581        // SAFETY: getting mutable slice can not make the string empty
582        unsafe { self.as_mut_string().as_mut_str() }
583    }
584
585    /// Returns contained string reference as [`NonEmptyStr`].
586    #[must_use]
587    pub const fn as_non_empty_str(&self) -> &NonEmptyStr {
588        // SAFETY: the string is non-empty by construction
589        unsafe { NonEmptyStr::from_str_unchecked(self.as_str()) }
590    }
591
592    /// Returns contained mutable string reference as [`NonEmptyStr`].
593    pub const fn as_non_empty_mut_str(&mut self) -> &mut NonEmptyStr {
594        // SAFETY: the string is non-empty by construction
595        unsafe { NonEmptyStr::from_mut_str_unchecked(self.as_mut_str()) }
596    }
597
598    /// Returns the underlying bytes of the string.
599    #[must_use]
600    pub const fn as_bytes(&self) -> &Bytes {
601        self.as_str().as_bytes()
602    }
603
604    /// Returns the underlying mutable bytes of the string.
605    ///
606    /// # Safety
607    ///
608    /// The caller must ensure that the bytes remain valid UTF-8.
609    pub const unsafe fn as_bytes_mut(&mut self) -> &mut Bytes {
610        // SAFETY: getting mutable bytes can not make the string empty
611        // moreover, the caller must ensure that the bytes remain valid UTF-8
612        unsafe { self.as_mut_str().as_bytes_mut() }
613    }
614
615    /// Returns the underlying bytes of the string as [`NonEmptyBytes`].
616    #[must_use]
617    pub const fn as_non_empty_bytes(&self) -> &NonEmptyBytes {
618        self.as_non_empty_str().as_non_empty_bytes()
619    }
620
621    /// Returns the underlying mutable bytes of the string as [`NonEmptyBytes`].
622    ///
623    /// # Safety
624    ///
625    /// The caller must ensure that the bytes remain valid UTF-8.
626    pub const unsafe fn as_non_empty_bytes_mut(&mut self) -> &mut NonEmptyBytes {
627        // SAFETY: the caller must ensure that the bytes remain valid UTF-8
628        unsafe { self.as_non_empty_mut_str().as_non_empty_bytes_mut() }
629    }
630
631    /// Returns the contained string reference.
632    #[must_use]
633    pub const fn as_string(&self) -> &String {
634        #[cfg(feature = "unsafe-assert")]
635        self.assert_non_empty();
636
637        self.as_string_no_assert()
638    }
639
640    /// Similar to [`from_non_empty_utf8_lossy`], but accepts the possibility of empty bytes.
641    ///
642    /// # Errors
643    ///
644    /// Returns [`EmptySlice`] if the given bytes are empty.
645    ///
646    /// [`from_non_empty_utf8_lossy`]: Self::from_non_empty_utf8_lossy
647    pub fn from_utf8_lossy(bytes: &Bytes) -> Result<NonEmptyCowStr<'_>, EmptySlice> {
648        NonEmptyBytes::try_from_slice(bytes).map(Self::from_non_empty_utf8_lossy)
649    }
650
651    /// Similar to [`from_non_empty_utf8_lossy_owned`], but
652    /// accepts the possibility of empty byte vectors.
653    ///
654    /// # Errors
655    ///
656    /// Returns [`EmptyByteVec`] if the given byte vector is empty.
657    ///
658    /// [`from_non_empty_utf8_lossy_owned`]: Self::from_non_empty_utf8_lossy_owned
659    pub fn from_utf8_lossy_owned(bytes: ByteVec) -> Result<Self, EmptyByteVec> {
660        NonEmptyByteVec::new(bytes).map(Self::from_non_empty_utf8_lossy_owned)
661    }
662
663    /// Converts the given [`NonEmptyBytes`] to non-empty string, including invalid characters.
664    ///
665    /// Any invalid UTF-8 sequences will be replaced with [`char::REPLACEMENT_CHARACTER`].
666    ///
667    /// This function returns [`NonEmptyCowStr<'_>`], since it may borrow the input bytes
668    /// in case they are valid UTF-8, or allocate new non-empty string otherwise.
669    #[must_use]
670    pub fn from_non_empty_utf8_lossy(non_empty: &NonEmptyBytes) -> NonEmptyCowStr<'_> {
671        match String::from_utf8_lossy(non_empty.as_slice()) {
672            // SAFETY: passing non-empty bytes results in non-empty lossy string
673            Cow::Owned(string) => Cow::Owned(unsafe { Self::new_unchecked(string) }),
674            Cow::Borrowed(string) => {
675                // SAFETY: bytes are valid and non-empty, so this is safe
676                Cow::Borrowed(unsafe { NonEmptyStr::from_str_unchecked(string) })
677            }
678        }
679    }
680
681    /// Converts the given [`NonEmptyByteVec`] to non-empty string, including invalid characters.
682    ///
683    /// Any invalid UTF-8 sequences will be replaced with [`char::REPLACEMENT_CHARACTER`].
684    ///
685    /// This function does not guarantee reuse of the original byte vector allocation.
686    #[must_use]
687    pub fn from_non_empty_utf8_lossy_owned(non_empty: NonEmptyByteVec) -> Self {
688        let cow = Self::from_non_empty_utf8_lossy(non_empty.as_non_empty_slice());
689
690        if let Cow::Owned(string) = cow {
691            string
692        } else {
693            // SAFETY: if `from_non_empty_utf8_lossy` returns `Cow::Borrowed`, it is valid UTF-8
694            // moreover, the bytes are non-empty by construction, so this is safe
695            unsafe { Self::from_non_empty_utf8_unchecked(non_empty) }
696        }
697    }
698
699    /// Converts the given byte vector to non-empty string if it is non-empty and valid UTF-8.
700    ///
701    /// # Errors
702    ///
703    /// Returns [`FromMaybeEmptyUtf8Error`] if the byte vector is empty or invalid UTF-8.
704    pub fn from_utf8(bytes: ByteVec) -> Result<Self, FromMaybeEmptyUtf8Error> {
705        let non_empty = NonEmptyByteVec::new(bytes)?;
706
707        let string = Self::from_non_empty_utf8(non_empty)?;
708
709        Ok(string)
710    }
711
712    /// Converts the given [`NonEmptyByteVec`] to non-empty string if it is valid UTF-8.
713    ///
714    /// # Errors
715    ///
716    /// Returns [`FromNonEmptyUtf8Error`] if the byte vector is invalid UTF-8.
717    pub fn from_non_empty_utf8(non_empty: NonEmptyByteVec) -> Result<Self, FromNonEmptyUtf8Error> {
718        let string = String::from_utf8(non_empty.into_vec()).map_err(|error| {
719            let non_empty_error = error.utf8_error().into();
720
721            // SAFETY: reclaiming ownership of previously passed non-empty bytes is safe
722            let non_empty = unsafe { NonEmptyByteVec::new_unchecked(error.into_bytes()) };
723
724            FromNonEmptyUtf8Error::new(non_empty_error, non_empty)
725        })?;
726
727        // SAFETY: the bytes are non-empty by construction, so is the resulting string
728        Ok(unsafe { Self::new_unchecked(string) })
729    }
730
731    /// Constructs [`Self`] from the given [`NonEmptyByteVec`] without checking for UTF-8 validity.
732    ///
733    /// # Safety
734    ///
735    /// The caller must ensure that the non-empty byte vector is valid UTF-8.
736    #[must_use]
737    pub unsafe fn from_non_empty_utf8_unchecked(non_empty: NonEmptyByteVec) -> Self {
738        // SAFETY: the caller must ensure that the bytes are valid UTF-8
739        // moreover, the bytes are non-empty by construction, so is the resulting string
740        unsafe { Self::from_utf8_unchecked(non_empty.into_vec()) }
741    }
742
743    /// Constructs [`Self`] from the given byte vector without
744    /// checking for emptiness or UTF-8 validity.
745    ///
746    /// # Safety
747    ///
748    /// The caller must ensure that the byte vector is non-empty and valid UTF-8.
749    #[must_use]
750    pub unsafe fn from_utf8_unchecked(bytes: ByteVec) -> Self {
751        // SAFETY: the caller must ensure that the bytes are non-empty and valid UTF-8
752        unsafe { Self::new_unchecked(String::from_utf8_unchecked(bytes)) }
753    }
754
755    /// Returns the contained mutable string reference.
756    ///
757    /// # Safety
758    ///
759    /// The caller must ensure that the string remains non-empty.
760    #[must_use]
761    pub const unsafe fn as_mut_string(&mut self) -> &mut String {
762        #[cfg(feature = "unsafe-assert")]
763        self.assert_non_empty();
764
765        // SAFETY: the caller must ensure that the string remains non-empty
766        unsafe { self.as_mut_string_no_assert() }
767    }
768
769    /// Returns the contained [`String`].
770    #[must_use]
771    pub fn into_string(self) -> String {
772        #[cfg(feature = "unsafe-assert")]
773        self.assert_non_empty();
774
775        self.into_string_no_assert()
776    }
777
778    /// Converts [`Self`] into the underlying byte vector.
779    #[must_use]
780    pub fn into_bytes(self) -> ByteVec {
781        self.into_string().into_bytes()
782    }
783
784    /// Converts [`Self`] into the underlying byte vector as [`NonEmptyByteVec`].
785    #[must_use]
786    pub fn into_non_empty_bytes(self) -> NonEmptyByteVec {
787        // SAFETY: the string is non-empty by construction, so are its bytes
788        unsafe { NonEmptyByteVec::new_unchecked(self.into_bytes()) }
789    }
790
791    /// Appends the given [`char`] to the end of this string.
792    pub fn push(&mut self, character: char) {
793        // SAFETY: pushing can not make the string empty
794        unsafe {
795            self.as_mut_string().push(character);
796        }
797    }
798
799    /// Appends the given [`str`] onto the end of this string.
800    pub fn push_str(&mut self, string: &str) {
801        // SAFETY: pushing can not make the string empty
802        unsafe {
803            self.as_mut_string().push_str(string);
804        }
805    }
806
807    /// Copies bytes from the given range to the end of the string.
808    ///
809    /// # Panics
810    ///
811    /// Panics if the range is out of bounds or not on character boundaries.
812    pub fn extend_from_within<R: RangeBounds<usize>>(&mut self, source: R) {
813        // SAFETY: extending can not make the string empty
814        unsafe {
815            self.as_mut_string().extend_from_within(source);
816        }
817    }
818
819    /// Appends anything that can be converted to string onto the end of this string.
820    pub fn extend_from<S: AsRef<str>>(&mut self, string: S) {
821        self.push_str(string.as_ref());
822    }
823
824    /// Reserves capacity for at least `additional` more bytes to be added.
825    ///
826    /// Note that the additional capacity is required to be non-zero via [`Size`].
827    ///
828    /// This method can over-allocate to speculatively avoid frequent reallocations.
829    ///
830    /// Does nothing if the capacity is already sufficient.
831    ///
832    /// # Panics
833    ///
834    /// Panics on capacity overflow.
835    pub fn reserve(&mut self, additional: Size) {
836        // SAFETY: reserving can not make the string empty
837        unsafe {
838            self.as_mut_string().reserve(additional.get());
839        }
840    }
841
842    /// Reserves the minimum capacity for exactly `additional` more values to be added.
843    ///
844    /// Note that the additional capacity is required to be non-zero via [`Size`].
845    ///
846    /// Unlike [`reserve`], this method will not deliberately over-allocate
847    /// to speculatively avoid frequent reallocations.
848    ///
849    /// Does nothing if the capacity is already sufficient.
850    ///
851    /// # Panics
852    ///
853    /// Panics on capacity overflow.
854    ///
855    /// [`reserve`]: Self::reserve
856    pub fn reserve_exact(&mut self, additional: Size) {
857        // SAFETY: reserving can not make the string empty
858        unsafe {
859            self.as_mut_string().reserve_exact(additional.get());
860        }
861    }
862
863    /// Tries to reserve capacity for at least `additional` more bytes to be added.
864    ///
865    /// Note that the additional capacity is required to be non-zero via [`Size`].
866    ///
867    /// This method can over-allocate to speculatively avoid frequent reallocations.
868    ///
869    /// Does nothing if the capacity is already sufficient.
870    ///
871    /// # Errors
872    ///
873    /// Returns [`TryReserveError`] if the allocation fails or capacity overflows.
874    pub fn try_reserve(&mut self, additional: Size) -> Result<(), TryReserveError> {
875        // SAFETY: reserving can not make the string empty
876        unsafe { self.as_mut_string().try_reserve(additional.get()) }
877    }
878
879    /// Tries to reserve the minimum capacity for exactly `additional` more bytes to be added.
880    ///
881    /// Note that the additional capacity is required to be non-zero via [`Size`].
882    ///
883    /// Unlike [`try_reserve`], this method will not deliberately over-allocate
884    /// to speculatively avoid frequent reallocations.
885    ///
886    /// Does nothing if the capacity is already sufficient.
887    ///
888    /// # Errors
889    ///
890    /// Returns [`TryReserveError`] if the allocation fails or capacity overflows.
891    ///
892    /// [`try_reserve`]: Self::try_reserve
893    pub fn try_reserve_exact(&mut self, additional: Size) -> Result<(), TryReserveError> {
894        // SAFETY: reserving can not make the string empty
895        unsafe { self.as_mut_string().try_reserve_exact(additional.get()) }
896    }
897
898    /// Shrinks the capacity of the string as much as possible.
899    pub fn shrink_to_fit(&mut self) {
900        // SAFETY: shrinking can not make the string empty
901        unsafe {
902            self.as_mut_string().shrink_to_fit();
903        }
904    }
905
906    /// Shrinks the capacity of the string to the specified amount.
907    ///
908    /// The capacity will remain at least as large as both the length and the supplied amount.
909    ///
910    /// Does nothing if the current capacity is less than or equal to the specified amount.
911    pub fn shrink_to(&mut self, capacity: Size) {
912        // SAFETY: shrinking can not make the string empty
913        unsafe {
914            self.as_mut_string().shrink_to(capacity.get());
915        }
916    }
917
918    /// Shortens this string to the specified non-zero length.
919    ///
920    /// Does nothing if `new` is greater than or equal to the string's [`len`].
921    ///
922    /// [`len`]: Self::len
923    pub fn truncate(&mut self, new: Size) {
924        // SAFETY: truncating to non-zero length can not make the string empty
925        unsafe {
926            self.as_mut_string().truncate(new.get());
927        }
928    }
929
930    /// Checks whether the string is almost empty, meaning it only contains one character.
931    #[must_use]
932    pub fn next_empty(&self) -> bool {
933        let (character, _) = self.chars().consume();
934
935        self.len().get() - character.len_utf8() == 0
936    }
937
938    /// The negated version of [`next_empty`].
939    ///
940    /// [`next_empty`]: Self::next_empty
941    #[must_use]
942    pub fn next_non_empty(&self) -> bool {
943        !self.next_empty()
944    }
945
946    /// Removes the last character from the string and returns it,
947    /// or [`None`] if the string would become empty.
948    pub fn pop(&mut self) -> Option<char> {
949        self.next_non_empty()
950            // SAFETY: popping only when the string would remain non-empty
951            .then(|| unsafe { self.as_mut_string().pop() })
952            .flatten()
953    }
954
955    /// Consumes and leaks the string, returning the mutable reference of its contents.
956    #[must_use]
957    pub fn leak<'a>(self) -> &'a mut str {
958        self.into_string().leak()
959    }
960
961    /// Similar to [`leak`], but returns [`NonEmptyStr`].
962    ///
963    /// [`leak`]: Self::leak
964    #[must_use]
965    pub fn leak_non_empty<'a>(self) -> &'a mut NonEmptyStr {
966        // SAFETY: the string is non-empty by construction, so is the leaked string
967        unsafe { NonEmptyStr::from_mut_str_unchecked(self.leak()) }
968    }
969
970    /// Inserts the given character at the specified index,
971    /// shifting all bytes after it to the right.
972    ///
973    /// # Panics
974    ///
975    /// Panics if the index is out of bounds or not on character boundary.
976    pub fn insert(&mut self, index: usize, character: char) {
977        // SAFETY: inserting can not make the string empty
978        unsafe {
979            self.as_mut_string().insert(index, character);
980        }
981    }
982
983    /// Inserts the given string at the specified index, shifting all bytes after it to the right.
984    ///
985    /// # Panics
986    ///
987    /// Panics if the index is out of bounds or not on character boundary.
988    pub fn insert_str(&mut self, index: usize, string: &str) {
989        // SAFETY: inserting can not make the string empty
990        unsafe {
991            self.as_mut_string().insert_str(index, string);
992        }
993    }
994
995    /// Inserts anything that can be converted to string at the specified index,
996    /// shifting all bytes after it to the right.
997    ///
998    /// # Panics
999    ///
1000    /// Panics if the index is out of bounds or not on character boundary.
1001    pub fn insert_from<S: AsRef<str>>(&mut self, index: usize, string: S) {
1002        self.insert_str(index, string.as_ref());
1003    }
1004
1005    /// Removes and returns the character at the given index within the string,
1006    /// shifting all bytes after it to the left.
1007    ///
1008    /// Returns [`None`] if the string would become empty.
1009    ///
1010    /// # Panics
1011    ///
1012    /// Panics if the index is out of bounds or not on character boundary.
1013    pub fn remove(&mut self, index: usize) -> Option<char> {
1014        self.next_non_empty()
1015            // SAFETY: removing only when the string would remain non-empty
1016            .then(|| unsafe { self.as_mut_string().remove(index) })
1017    }
1018
1019    /// Splits the string into two at the given non-zero index.
1020    ///
1021    /// The index has to be non-zero to guaratee that the string would remain non-empty.
1022    ///
1023    /// # Panics
1024    ///
1025    /// Panics if the provided index is out of bounds or not on character boundary.
1026    pub fn split_off(&mut self, at: Size) -> String {
1027        // SAFETY: splitting at non-zero index can not make the string empty
1028        unsafe { self.as_mut_string().split_off(at.get()) }
1029    }
1030}
1031
1032impl ToOwned for NonEmptyStr {
1033    type Owned = NonEmptyString;
1034
1035    fn to_owned(&self) -> Self::Owned {
1036        self.to_non_empty_string()
1037    }
1038}
1039
1040impl NonEmptyStr {
1041    /// Converts [`Self`] to [`NonEmptyString`] via cloning.
1042    #[must_use]
1043    pub fn to_non_empty_string(&self) -> NonEmptyString {
1044        NonEmptyString::from_non_empty_str(self)
1045    }
1046
1047    /// Converts [`Self`] to [`NonEmptyByteVec`] via cloning.
1048    #[must_use]
1049    pub fn to_non_empty_bytes(&self) -> NonEmptyByteVec {
1050        self.to_non_empty_string().into_non_empty_bytes()
1051    }
1052
1053    /// Converts this string to its lowercase equivalent.
1054    #[must_use]
1055    pub fn to_lowercase(&self) -> String {
1056        self.as_str().to_lowercase()
1057    }
1058
1059    /// Converts this string to its uppercase equivalent.
1060    #[must_use]
1061    pub fn to_uppercase(&self) -> String {
1062        self.as_str().to_uppercase()
1063    }
1064
1065    /// Creates [`NonEmptyString`] by repeating this string certain number of times.
1066    ///
1067    /// Note that the count is non-zero in order to guarantee that
1068    /// the resulting string is non-empty.
1069    ///
1070    /// # Panics
1071    ///
1072    /// Panics on capacity overflow.
1073    #[must_use]
1074    pub fn repeat(&self, count: Size) -> NonEmptyString {
1075        let non_empty = self.as_str().repeat(count.get());
1076
1077        // SAFETY: repeating non-empty string non-zero times results in non-empty string
1078        unsafe { NonEmptyString::new_unchecked(non_empty) }
1079    }
1080
1081    /// Converts this string to its lowercase equivalent as [`NonEmptyString`].
1082    #[must_use]
1083    pub fn to_non_empty_lowercase(&self) -> NonEmptyString {
1084        // SAFETY: converting non-empty string to lowercase gives non-empty output
1085        unsafe { NonEmptyString::new_unchecked(self.to_lowercase()) }
1086    }
1087
1088    /// Converts this string to its uppercase equivalent as [`NonEmptyString`].
1089    #[must_use]
1090    pub fn to_non_empty_uppercase(&self) -> NonEmptyString {
1091        // SAFETY: converting non-empty string to uppercase gives non-empty output
1092        unsafe { NonEmptyString::new_unchecked(self.to_uppercase()) }
1093    }
1094}
1095
1096impl NonEmptyString {
1097    /// Constructs [`Self`] containing single provided character.
1098    #[must_use]
1099    pub fn single(character: char) -> Self {
1100        // SAFETY: non-empty construction
1101        unsafe { Self::new_unchecked(character.to_string()) }
1102    }
1103
1104    /// Constructs [`Self`] with the specified capacity in bytes, pushing the provided character.
1105    #[must_use]
1106    pub fn with_capacity_and_char(capacity: Size, character: char) -> Self {
1107        let mut string = String::with_capacity(capacity.get());
1108
1109        string.push(character);
1110
1111        // SAFETY: non-empty construction
1112        unsafe { Self::new_unchecked(string) }
1113    }
1114}
1115
1116impl FromNonEmptyIterator<char> for NonEmptyString {
1117    fn from_non_empty_iter<I: IntoNonEmptyIterator<Item = char>>(iterable: I) -> Self {
1118        let (character, iterator) = iterable.into_non_empty_iter().consume();
1119
1120        let mut output = Self::single(character);
1121
1122        output.extend(iterator);
1123
1124        output
1125    }
1126}
1127
1128impl<'c> FromNonEmptyIterator<&'c char> for NonEmptyString {
1129    fn from_non_empty_iter<I: IntoNonEmptyIterator<Item = &'c char>>(iterable: I) -> Self {
1130        let (&character, iterator) = iterable.into_non_empty_iter().consume();
1131
1132        let mut output = Self::single(character);
1133
1134        output.extend(iterator);
1135
1136        output
1137    }
1138}
1139
1140impl<'s> FromNonEmptyIterator<&'s NonEmptyStr> for NonEmptyString {
1141    fn from_non_empty_iter<I: IntoNonEmptyIterator<Item = &'s NonEmptyStr>>(iterable: I) -> Self {
1142        let (non_empty, iterator) = iterable.into_non_empty_iter().consume();
1143
1144        let mut output = Self::from_non_empty_str(non_empty);
1145
1146        output.extend(iterator);
1147
1148        output
1149    }
1150}
1151
1152impl FromNonEmptyIterator<Self> for NonEmptyString {
1153    fn from_non_empty_iter<I: IntoNonEmptyIterator<Item = Self>>(iterable: I) -> Self {
1154        let (mut output, iterator) = iterable.into_non_empty_iter().consume();
1155
1156        output.extend(iterator);
1157
1158        output
1159    }
1160}
1161
1162impl FromNonEmptyIterator<NonEmptyBoxedStr> for NonEmptyString {
1163    fn from_non_empty_iter<I: IntoNonEmptyIterator<Item = NonEmptyBoxedStr>>(iterable: I) -> Self {
1164        let (non_empty, iterator) = iterable.into_non_empty_iter().consume();
1165
1166        let mut output = Self::from_non_empty_boxed_str(non_empty);
1167
1168        output.extend(iterator);
1169
1170        output
1171    }
1172}
1173
1174impl<'s> FromNonEmptyIterator<NonEmptyCowStr<'s>> for NonEmptyString {
1175    fn from_non_empty_iter<I: IntoNonEmptyIterator<Item = NonEmptyCowStr<'s>>>(
1176        iterable: I,
1177    ) -> Self {
1178        let (non_empty, iterator) = iterable.into_non_empty_iter().consume();
1179
1180        let mut output = non_empty.into_owned();
1181
1182        output.extend(iterator);
1183
1184        output
1185    }
1186}