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
494
495
//! A non-empty [slice][`prim@slice`].

#[cfg(feature = "serde")]
use ::serde::{Deserialize, Deserializer};
use core::fmt::{self, Debug, Formatter};
use core::mem;
use core::num::NonZeroUsize;
use core::ops::{Deref, DerefMut, Index, IndexMut};
use core::slice::{self, Chunks, ChunksMut, RChunks, RChunksMut};
#[cfg(feature = "rayon")]
use rayon::iter::{IntoParallelIterator, IntoParallelRefIterator, IntoParallelRefMutIterator};
#[cfg(feature = "schemars")]
use {
    alloc::borrow::Cow,
    schemars::{JsonSchema, Schema, SchemaGenerator},
};
#[cfg(feature = "alloc")]
use {alloc::borrow::ToOwned, alloc::vec::Vec};

use crate::iter1::{IntoIterator1, Iterator1};
#[cfg(feature = "rayon")]
use crate::iter1::{IntoParallelIterator1, ParallelIterator1};
use crate::safety;
use crate::{Cardinality, EmptyError, FromMaybeEmpty, MaybeEmpty, NonEmpty};
#[cfg(feature = "alloc")]
use {crate::boxed1::BoxedSlice1, crate::vec1::Vec1};

unsafe impl<T> MaybeEmpty for [T] {
    fn cardinality(&self) -> Option<Cardinality<(), ()>> {
        match self.len() {
            0 => None,
            1 => Some(Cardinality::One(())),
            _ => Some(Cardinality::Many(())),
        }
    }
}

pub type Slice1<T> = NonEmpty<[T]>;

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

    /// # Safety
    ///
    /// `items` must be non-empty. For example, it is undefined behavior to call this function with
    /// an empty slice literal `&mut []`.
    pub const unsafe fn from_mut_slice_unchecked(items: &mut [T]) -> &mut Self {
        // SAFETY: `NonEmpty` is `repr(transparent)`, so the representations of `[T]` and
        //         `Slice1<T>` are the same.
        unsafe { mem::transmute::<&'_ mut [T], &'_ mut Slice1<T>>(items) }
    }

    pub fn try_from_slice(items: &[T]) -> Result<&Self, EmptyError<&[T]>> {
        items.try_into()
    }

    pub fn try_from_mut_slice(items: &mut [T]) -> Result<&mut Self, EmptyError<&mut [T]>> {
        items.try_into()
    }

    #[cfg(feature = "alloc")]
    #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
    pub fn to_vec1(&self) -> Vec1<T>
    where
        T: Clone,
    {
        Vec1::from(self)
    }

    #[cfg(feature = "alloc")]
    #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
    pub fn into_vec1(self: BoxedSlice1<T>) -> Vec1<T> {
        Vec1::from(self)
    }

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

    pub const fn split_first(&self) -> (&T, &[T]) {
        // SAFETY: `self` must be non-empty.
        unsafe { safety::unwrap_option_maybe_unchecked(self.items.split_first()) }
    }

    pub const fn split_first_mut(&mut self) -> (&mut T, &mut [T]) {
        // SAFETY: `self` must be non-empty.
        unsafe { safety::unwrap_option_maybe_unchecked(self.items.split_first_mut()) }
    }

    pub const fn first(&self) -> &T {
        // SAFETY: `self` must be non-empty.
        unsafe { safety::unwrap_option_maybe_unchecked(self.items.first()) }
    }

    pub const fn first_mut(&mut self) -> &mut T {
        // SAFETY: `self` must be non-empty.
        unsafe { safety::unwrap_option_maybe_unchecked(self.items.first_mut()) }
    }

    pub const fn last(&self) -> &T {
        // SAFETY: `self` must be non-empty.
        unsafe { safety::unwrap_option_maybe_unchecked(self.items.last()) }
    }

    pub const fn last_mut(&mut self) -> &mut T {
        // SAFETY: `self` must be non-empty.
        unsafe { safety::unwrap_option_maybe_unchecked(self.items.last_mut()) }
    }

    pub fn chunks1(&self, n: usize) -> Iterator1<Chunks<'_, T>> {
        // SAFETY: This iterator cannot have a cardinality of zero.
        unsafe { Iterator1::from_iter_unchecked(self.items.chunks(n)) }
    }

    pub fn chunks1_mut(&mut self, n: usize) -> Iterator1<ChunksMut<'_, T>> {
        // SAFETY: This iterator cannot have a cardinality of zero.
        unsafe { Iterator1::from_iter_unchecked(self.items.chunks_mut(n)) }
    }

    pub fn rchunks1(&self, n: usize) -> Iterator1<RChunks<'_, T>> {
        // SAFETY: This iterator cannot have a cardinality of zero.
        unsafe { Iterator1::from_iter_unchecked(self.items.rchunks(n)) }
    }

    pub fn rchunks1_mut(&mut self, n: usize) -> Iterator1<RChunksMut<'_, T>> {
        // SAFETY: This iterator cannot have a cardinality of zero.
        unsafe { Iterator1::from_iter_unchecked(self.items.rchunks_mut(n)) }
    }

    pub fn iter1(&self) -> Iterator1<slice::Iter<'_, T>> {
        // SAFETY: `self` must be non-empty.
        unsafe { Iterator1::from_iter_unchecked(self.as_slice().iter()) }
    }

    pub fn iter1_mut(&mut self) -> Iterator1<slice::IterMut<'_, T>> {
        // SAFETY: `self` must be non-empty.
        unsafe { Iterator1::from_iter_unchecked(self.as_mut_slice().iter_mut()) }
    }

    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_slice(&self) -> &'_ [T] {
        &self.items
    }

    pub const fn as_mut_slice(&mut self) -> &'_ mut [T] {
        &mut self.items
    }
}

#[cfg(feature = "rayon")]
#[cfg_attr(docsrs, doc(cfg(feature = "rayon")))]
impl<T> Slice1<T> {
    pub fn par_iter1(&self) -> ParallelIterator1<<&'_ Self as IntoParallelIterator>::Iter>
    where
        T: Sync,
    {
        unsafe { ParallelIterator1::from_par_iter_unchecked(self.par_iter()) }
    }

    pub fn par_iter1_mut(
        &mut self,
    ) -> ParallelIterator1<<&'_ mut Self as IntoParallelIterator>::Iter>
    where
        T: Send,
    {
        unsafe { ParallelIterator1::from_par_iter_unchecked(self.par_iter_mut()) }
    }
}

impl<T> AsMut<[T]> for Slice1<T> {
    fn as_mut(&mut self) -> &mut [T] {
        &mut self.items
    }
}

impl<T> Debug for Slice1<T>
where
    T: Debug,
{
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter
            .debug_list()
            .entries(self.as_slice().iter())
            .finish()
    }
}

impl<T> Deref for Slice1<T> {
    type Target = [T];

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

impl<T> DerefMut for Slice1<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.as_mut_slice()
    }
}

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

        let items = <&[u8]>::deserialize(deserializer)?;
        <&Slice1<u8>>::try_from(items).map_err(D::Error::custom)
    }
}

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl<'a, T> From<&'a Slice1<T>> for Vec<T>
where
    T: Clone,
{
    fn from(items: &'a Slice1<T>) -> Self {
        Vec::from(items.as_slice())
    }
}

impl<T, I> Index<I> for Slice1<T>
where
    [T]: Index<I>,
{
    type Output = <[T] as Index<I>>::Output;

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

impl<T, I> IndexMut<I> for Slice1<T>
where
    [T]: IndexMut<I>,
{
    fn index_mut(&mut self, at: I) -> &mut Self::Output {
        self.items.index_mut(at)
    }
}

impl<'a, T> IntoIterator for &'a Slice1<T> {
    type Item = &'a T;
    type IntoIter = slice::Iter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.items.iter()
    }
}

impl<'a, T> IntoIterator for &'a mut Slice1<T> {
    type Item = &'a mut T;
    type IntoIter = slice::IterMut<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.items.iter_mut()
    }
}

impl<T> IntoIterator1 for &'_ Slice1<T> {
    fn into_iter1(self) -> Iterator1<Self::IntoIter> {
        self.iter1()
    }
}

impl<T> IntoIterator1 for &'_ mut Slice1<T> {
    fn into_iter1(self) -> Iterator1<Self::IntoIter> {
        self.iter1_mut()
    }
}

#[cfg(feature = "rayon")]
#[cfg_attr(docsrs, doc(cfg(feature = "rayon")))]
impl<'a, T> IntoParallelIterator for &'a Slice1<T>
where
    T: Sync,
{
    type Item = &'a T;
    type Iter = <&'a [T] as IntoParallelIterator>::Iter;

    fn into_par_iter(self) -> Self::Iter {
        (&self.items).into_par_iter()
    }
}

#[cfg(feature = "rayon")]
#[cfg_attr(docsrs, doc(cfg(feature = "rayon")))]
impl<'a, T> IntoParallelIterator for &'a mut Slice1<T>
where
    T: Send,
{
    type Item = &'a mut T;
    type Iter = <&'a mut [T] as IntoParallelIterator>::Iter;

    fn into_par_iter(self) -> Self::Iter {
        (&mut self.items).into_par_iter()
    }
}

#[cfg(feature = "rayon")]
#[cfg_attr(docsrs, doc(cfg(feature = "rayon")))]
impl<T> IntoParallelIterator1 for &'_ Slice1<T>
where
    T: Sync,
{
    fn into_par_iter1(self) -> ParallelIterator1<Self::Iter> {
        // SAFETY: `self` must be non-empty.
        unsafe { ParallelIterator1::from_par_iter_unchecked(&self.items) }
    }
}

#[cfg(feature = "rayon")]
#[cfg_attr(docsrs, doc(cfg(feature = "rayon")))]
impl<T> IntoParallelIterator1 for &'_ mut Slice1<T>
where
    T: Send,
{
    fn into_par_iter1(self) -> ParallelIterator1<Self::Iter> {
        // SAFETY: `self` must be non-empty.
        unsafe { ParallelIterator1::from_par_iter_unchecked(&mut self.items) }
    }
}

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

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

        schemars::json_subschema_with_non_empty_property_for::<[T]>(
            schemars::NON_EMPTY_KEY_ARRAY,
            generator,
        )
    }

    fn inline_schema() -> bool {
        <[T]>::inline_schema()
    }

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

crate::impl_partial_eq_for_non_empty!([for U in [U]] <= [for T in Slice1<T>]);
crate::impl_partial_eq_for_non_empty!([for U in Slice1<U>] => [for T in [T]]);

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl<T> ToOwned for Slice1<T>
where
    T: Clone,
{
    type Owned = Vec1<T>;

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

impl<'a, T> TryFrom<&'a [T]> for &'a Slice1<T> {
    type Error = EmptyError<&'a [T]>;

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

impl<'a, T> TryFrom<&'a mut [T]> for &'a mut Slice1<T> {
    type Error = EmptyError<&'a mut [T]>;

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

pub const fn from_ref<T>(item: &T) -> &Slice1<T> {
    // SAFETY: The input slice is non-empty.
    unsafe { Slice1::from_slice_unchecked(slice::from_ref(item)) }
}

pub fn from_mut<T>(item: &mut T) -> &mut Slice1<T> {
    // SAFETY: The input slice is non-empty.
    unsafe { Slice1::from_mut_slice_unchecked(slice::from_mut(item)) }
}

#[macro_export]
macro_rules! slice1 {
    ($($item:expr $(,)?)+) => {{
        let slice: &[_] = &[$($item,)+];
        // SAFETY: There must be one or more `item` metavariables in the repetition.
        unsafe { $crate::slice1::Slice1::from_slice_unchecked(slice) }
    }};
}
pub use slice1;

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

    use crate::slice1::Slice1;

    #[fixture]
    pub fn xs1() -> &'static Slice1<u8> {
        slice1![0, 1, 2, 3, 4]
    }
}

#[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::slice1::Slice1;
    #[cfg(feature = "serde")]
    use {
        crate::serde::{
            self,
            harness::{borrowed_bytes, sequence},
        },
        crate::slice1::harness::xs1,
    };

    #[cfg(feature = "schemars")]
    #[rstest]
    fn slice1_json_schema_has_non_empty_property() {
        schemars::harness::assert_json_schema_has_non_empty_property::<Slice1<u8>>(
            schemars::NON_EMPTY_KEY_ARRAY,
        );
    }

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

    #[cfg(feature = "serde")]
    #[rstest]
    fn serialize_slice1_into_tokens_eq(xs1: &Slice1<u8>, sequence: impl Iterator<Item = Token>) {
        serde::harness::assert_into_tokens_eq::<_, Vec<_>>(xs1, sequence)
    }
}