mitsein 0.9.0

Strongly typed APIs for non-empty collections, slices, and iterators.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
//! A non-empty [str][`prim@str`].

#[cfg(feature = "serde")]
use ::serde::{Deserialize, Deserializer};
#[cfg(feature = "arbitrary")]
use arbitrary::{Arbitrary, Unstructured};
use core::fmt::{self, Debug, Display, Formatter};
use core::mem;
use core::num::NonZeroUsize;
use core::ops::{Deref, DerefMut, Index, IndexMut};
use core::slice::SliceIndex;
use core::str::{
    self, Bytes, CharIndices, Chars, EncodeUtf16, Lines, Split, SplitInclusive, SplitTerminator,
    Utf8Error,
};
#[cfg(feature = "rayon")]
use rayon::str::ParallelString;
#[cfg(feature = "schemars")]
use {
    alloc::borrow::Cow,
    schemars::{JsonSchema, Schema, SchemaGenerator},
};
#[cfg(feature = "alloc")]
use {alloc::borrow::ToOwned, alloc::string::String};

use crate::iter1::Iterator1;
#[cfg(feature = "rayon")]
use crate::iter1::ParallelIterator1;
use crate::safety;
use crate::slice1::Slice1;
use crate::{Cardinality, EmptyError, FromMaybeEmpty, MaybeEmpty, NonEmpty};
#[cfg(feature = "alloc")]
use {crate::boxed1::BoxedStr1, crate::string1::String1};

unsafe impl MaybeEmpty for str {
    fn cardinality(&self) -> Option<Cardinality<(), ()>> {
        // Unlike other containers, the items (bytes) in UTF-8 encoded strings are incongruent with
        // the items manipulated by insertions and removals: code points (`char`s). Cardinality is
        // based on code points formed from the UTF-8 rather than the count of bytes. This can
        // present some edge cases, such as a non-zero number of invalid UTF-8 bytes that cannot be
        // interpreted as code points.
        match self.chars().take(2).count() {
            0 => None,
            1 => Some(Cardinality::One(())),
            _ => Some(Cardinality::Many(())),
        }
    }
}

pub type Str1 = NonEmpty<str>;

// TODO: At time of writing, `const` functions are not supported in traits, so
//       `FromMaybeEmpty::from_maybe_empty_unchecked` cannot be used to construct a `Str1` yet. Use
//       that function instead of `mem::transmute` when possible.
impl Str1 {
    /// # Safety
    ///
    /// `items` must be non-empty. For example, it is unsound to call this function with an empty
    /// string literal `""`.
    pub const unsafe fn from_str_unchecked(items: &str) -> &Self {
        // SAFETY: `NonEmpty` is `repr(transparent)`, so the representations of `str` and `Str1`
        //         are the same.
        unsafe { mem::transmute::<&'_ str, &'_ Str1>(items) }
    }

    /// # Safety
    ///
    /// `items` must be non-empty. For example, it is unsound to call this function with an empty
    /// string literal `""`.
    pub const unsafe fn from_mut_str_unchecked(items: &mut str) -> &mut Self {
        // SAFETY: `NonEmpty` is `repr(transparent)`, so the representations of `str` and `Str1`
        //         are the same.
        unsafe { mem::transmute::<&'_ mut str, &'_ mut Str1>(items) }
    }

    pub fn try_from_str(items: &str) -> Result<&Self, EmptyError<&str>> {
        items.try_into()
    }

    pub fn try_from_mut_str(items: &mut str) -> Result<&mut Self, EmptyError<&mut str>> {
        items.try_into()
    }

    #[cfg(feature = "alloc")]
    #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
    pub fn to_string1(&self) -> String1 {
        String1::from(self)
    }

    #[cfg(feature = "alloc")]
    #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
    pub fn into_string1(self: BoxedStr1) -> String1 {
        String1::from(self)
    }

    #[cfg(feature = "alloc")]
    #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
    pub fn once_and_then_repeat(&self, n: usize) -> String1 {
        // SAFETY: `self` must be non-empty.
        unsafe {
            String1::from_string_unchecked(
                self.items
                    .repeat(n.checked_add(1).expect("overflow in slice repetition")),
            )
        }
    }

    pub fn encode1_utf16(&self) -> Iterator1<EncodeUtf16<'_>> {
        // SAFETY: `self` must be non-empty.
        unsafe { Iterator1::from_iter_unchecked(self.encode_utf16()) }
    }

    pub fn split1<'a, P>(&'a self, separator: &'a P) -> Iterator1<Split<'a, &'a [char]>>
    where
        P: 'a + AsRef<[char]>,
    {
        // SAFETY: `self` must be non-empty.
        unsafe { Iterator1::from_iter_unchecked(self.split(separator.as_ref())) }
    }

    pub fn split1_inclusive<'a, P>(
        &'a self,
        separator: &'a P,
    ) -> Iterator1<SplitInclusive<'a, &'a [char]>>
    where
        P: 'a + AsRef<[char]>,
    {
        // SAFETY: `self` must be non-empty.
        unsafe { Iterator1::from_iter_unchecked(self.split_inclusive(separator.as_ref())) }
    }

    pub fn split1_terminator<'a, P>(
        &'a self,
        separator: &'a P,
    ) -> Iterator1<SplitTerminator<'a, &'a [char]>>
    where
        P: 'a + AsRef<[char]>,
    {
        // SAFETY: `self` must be non-empty.
        unsafe { Iterator1::from_iter_unchecked(self.split_terminator(separator.as_ref())) }
    }

    #[cfg(feature = "alloc")]
    pub(crate) fn first(&self) -> char {
        use crate::safety::OptionExt as _;

        // SAFETY: `self` must be non-empty.
        unsafe { self.items.chars().next().unwrap_maybe_unchecked() }
    }

    pub fn chars1(&self) -> Iterator1<Chars<'_>> {
        // SAFETY: `self` must be non-empty.
        unsafe { Iterator1::from_iter_unchecked(self.as_str().chars()) }
    }

    pub fn char_indices1(&self) -> Iterator1<CharIndices<'_>> {
        // SAFETY: `self` must be non-empty.
        unsafe { Iterator1::from_iter_unchecked(self.as_str().char_indices()) }
    }

    pub fn bytes1(&self) -> Iterator1<Bytes<'_>> {
        // SAFETY: `self` must be non-empty.
        unsafe { Iterator1::from_iter_unchecked(self.as_str().bytes()) }
    }

    pub fn lines1(&self) -> Iterator1<Lines<'_>> {
        // SAFETY: `self` must be non-empty.
        unsafe { Iterator1::from_iter_unchecked(self.as_str().lines()) }
    }

    pub const fn len(&self) -> NonZeroUsize {
        // SAFETY: `self` must be non-empty.
        unsafe { safety::non_zero_from_usize_maybe_unchecked(self.items.len()) }
    }

    pub const fn as_bytes1(&self) -> &Slice1<u8> {
        // SAFETY: `self` must be non-empty.
        unsafe { Slice1::from_slice_unchecked(self.as_str().as_bytes()) }
    }

    pub const fn as_bytes1_mut(&mut self) -> &mut Slice1<u8> {
        // SAFETY: `self` must be non-empty.
        unsafe { Slice1::from_mut_slice_unchecked(self.as_mut_str().as_bytes_mut()) }
    }

    pub const fn as_str(&self) -> &'_ str {
        &self.items
    }

    pub const fn as_mut_str(&mut self) -> &'_ mut str {
        &mut self.items
    }
}

#[cfg(feature = "rayon")]
#[cfg_attr(docsrs, doc(cfg(feature = "rayon")))]
impl Str1 {
    pub fn par_encode1_utf16(&self) -> ParallelIterator1<rayon::str::EncodeUtf16<'_>> {
        // SAFETY: `self` must be non-empty.
        unsafe { ParallelIterator1::from_par_iter_unchecked(self.par_encode_utf16()) }
    }

    pub fn par_split1<'a, P>(
        &'a self,
        separator: &'a P,
    ) -> ParallelIterator1<rayon::str::Split<'a, &'a [char]>>
    where
        P: 'a + AsRef<[char]>,
    {
        // SAFETY: `self` must be non-empty.
        unsafe { ParallelIterator1::from_par_iter_unchecked(self.par_split(separator.as_ref())) }
    }

    pub fn par_split1_inclusive<'a, P>(
        &'a self,
        separator: &'a P,
    ) -> ParallelIterator1<rayon::str::SplitInclusive<'a, &'a [char]>>
    where
        P: 'a + AsRef<[char]>,
    {
        // SAFETY: `self` must be non-empty.
        unsafe {
            ParallelIterator1::from_par_iter_unchecked(self.par_split_inclusive(separator.as_ref()))
        }
    }

    pub fn par_split1_terminator<'a, P>(
        &'a self,
        separator: &'a P,
    ) -> ParallelIterator1<rayon::str::SplitTerminator<'a, &'a [char]>>
    where
        P: 'a + AsRef<[char]>,
    {
        // SAFETY: `self` must be non-empty.
        unsafe {
            ParallelIterator1::from_par_iter_unchecked(
                self.par_split_terminator(separator.as_ref()),
            )
        }
    }

    pub fn par_chars1(&self) -> ParallelIterator1<rayon::str::Chars<'_>> {
        // SAFETY: `self` must be non-empty.
        unsafe { ParallelIterator1::from_par_iter_unchecked(self.par_chars()) }
    }

    pub fn par_char_indices1(&self) -> ParallelIterator1<rayon::str::CharIndices<'_>> {
        // SAFETY: `self` must be non-empty.
        unsafe { ParallelIterator1::from_par_iter_unchecked(self.par_char_indices()) }
    }

    pub fn par_bytes1(&self) -> ParallelIterator1<rayon::str::Bytes<'_>> {
        // SAFETY: `self` must be non-empty.
        unsafe { ParallelIterator1::from_par_iter_unchecked(self.par_bytes()) }
    }

    pub fn par_lines1(&self) -> ParallelIterator1<rayon::str::Lines<'_>> {
        // SAFETY: `self` must be non-empty.
        unsafe { ParallelIterator1::from_par_iter_unchecked(self.par_lines()) }
    }
}

#[cfg(feature = "arbitrary")]
#[cfg_attr(docsrs, doc(cfg(feature = "arbitrary")))]
impl<'a> Arbitrary<'a> for &'a Str1 {
    fn arbitrary(unstructured: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
        loop {
            if let Ok(items) = Str1::try_from_str(<&'a str>::arbitrary(unstructured)?) {
                break Ok(items);
            }
        }
    }

    fn size_hint(_: usize) -> (usize, Option<usize>) {
        (1, None)
    }
}

impl AsMut<str> for Str1 {
    fn as_mut(&mut self) -> &mut str {
        &mut self.items
    }
}

impl Debug for Str1 {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        write!(formatter, "{:?}", &self.items)
    }
}

impl Deref for Str1 {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl DerefMut for Str1 {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.as_mut_str()
    }
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<'a, 'de> Deserialize<'de> for &'a Str1
where
    'de: 'a,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        use ::serde::de::Error;

        let items = <&str>::deserialize(deserializer)?;
        <&Str1>::try_from(items).map_err(D::Error::custom)
    }
}

impl Display for Str1 {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}", &self.items)
    }
}

impl<'a> From<&'a Str1> for &'a str {
    fn from(items: &'a Str1) -> Self {
        &items.items
    }
}

impl<'a> From<&'a mut Str1> for &'a mut str {
    fn from(items: &'a mut Str1) -> Self {
        &mut items.items
    }
}

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl<'a> From<&'a Str1> for String {
    fn from(items: &'a Str1) -> Self {
        String::from(items.as_str())
    }
}

impl<I> Index<I> for Str1
where
    I: SliceIndex<str>,
{
    type Output = <I as SliceIndex<str>>::Output;

    fn index(&self, at: I) -> &Self::Output {
        self.items.index(at)
    }
}

impl<I> IndexMut<I> for Str1
where
    I: SliceIndex<str>,
{
    fn index_mut(&mut self, at: I) -> &mut Self::Output {
        self.items.index_mut(at)
    }
}

#[cfg(feature = "schemars")]
#[cfg_attr(docsrs, doc(cfg(feature = "schemars")))]
impl JsonSchema for Str1 {
    fn schema_name() -> Cow<'static, str> {
        <str>::schema_name()
    }

    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
        use crate::schemars;

        schemars::json_subschema_with_non_empty_property_for::<str>(
            schemars::NON_EMPTY_KEY_STRING,
            generator,
        )
    }

    fn inline_schema() -> bool {
        <str>::inline_schema()
    }

    fn schema_id() -> Cow<'static, str> {
        <str>::schema_id()
    }
}

crate::impl_partial_eq_for_non_empty!([in str] <= [in Str1]);
crate::impl_partial_eq_for_non_empty!([in Str1] => [in str]);

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl ToOwned for Str1 {
    type Owned = String1;

    fn to_owned(&self) -> Self::Owned {
        String1::from(self)
    }
}

impl<'a> TryFrom<&'a str> for &'a Str1 {
    type Error = EmptyError<&'a str>;

    fn try_from(items: &'a str) -> Result<Self, Self::Error> {
        FromMaybeEmpty::try_from_maybe_empty(items)
    }
}

impl<'a> TryFrom<&'a mut str> for &'a mut Str1 {
    type Error = EmptyError<&'a mut str>;

    fn try_from(items: &'a mut str) -> Result<Self, Self::Error> {
        FromMaybeEmpty::try_from_maybe_empty(items)
    }
}

// There is no counterpart to `str::from_utf8_unchecked` here, because it is not clear that a `str`
// consisting of one or more bytes of invalid UTF-8 will yield at least one `char` (code point) in
// its API. This forms a deceptively complex API, because both the data format and non-empty
// guarantees must be maintained by callers (despite accepting a `Slice1`). Contrast this with
// `Str1::from_str_unchecked`, which is only sensitive to the non-empty guarantee.
pub const fn from_utf8(items: &Slice1<u8>) -> Result<&Str1, Utf8Error> {
    match str::from_utf8(items.as_slice()) {
        // SAFETY: `items` is non-empty and `str::from_utf8` has parsed it as valid UTF-8, so there
        //         must be one or more code points.
        Ok(items) => Ok(unsafe { Str1::from_str_unchecked(items) }),
        Err(error) => Err(error),
    }
}

pub fn from_utf8_mut(items: &mut Slice1<u8>) -> Result<&mut Str1, Utf8Error> {
    match str::from_utf8_mut(items.as_mut_slice()) {
        // SAFETY: `items` is non-empty and `str::from_utf8_mut` has parsed it as valid UTF-8, so
        //         there must be one or more code points.
        Ok(items) => Ok(unsafe { Str1::from_mut_str_unchecked(items) }),
        Err(error) => Err(error),
    }
}

#[cfg(test)]
pub mod harness {
    use rstest::fixture;

    use crate::str1::Str1;

    #[fixture]
    pub fn xs1() -> &'static Str1 {
        Str1::try_from_str("non-empty").unwrap()
    }
}

#[cfg(all(
    test,
    any(feature = "schemars", all(feature = "alloc", feature = "serde"))
))]
mod tests {
    use rstest::rstest;
    #[cfg(feature = "serde")]
    use {alloc::vec::Vec, serde_test::Token};

    #[cfg(feature = "schemars")]
    use crate::schemars;
    use crate::str1::Str1;
    #[cfg(feature = "serde")]
    use {
        crate::serde::{self, harness::borrowed_str},
        crate::str1::harness::xs1,
    };

    #[cfg(feature = "schemars")]
    #[rstest]
    fn str1_json_schema_has_non_empty_property() {
        schemars::harness::assert_json_schema_has_non_empty_property::<Str1>(
            schemars::NON_EMPTY_KEY_STRING,
        );
    }

    #[cfg(feature = "serde")]
    #[rstest]
    fn deserialize_ref_slice1_u8_from_tokens_eq(
        xs1: &Str1,
        #[with(xs1)] borrowed_str: impl Iterator<Item = Token>,
    ) {
        let borrowed_str: Vec<_> = borrowed_str.collect();
        let borrowed_str = borrowed_str.as_slice();
        serde::harness::assert_ref_from_tokens_eq(xs1, borrowed_str)
    }
}