Skip to main content

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