Skip to main content

non_empty_str/
string.rs

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