arc-slice 0.1.0

Shared memory slices
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
//! [Small String Optimization] support for [`ArcSlice`].
//!
//! [Small String Optimization]: https://cppdepend.com/blog/understanding-small-string-optimization-sso-in-stdstring/

use alloc::{string::String, vec::Vec};
use core::{
    borrow::Borrow,
    cmp, fmt,
    hash::{Hash, Hasher},
    marker::PhantomData,
    mem::{size_of, ManuallyDrop, MaybeUninit},
    ops::{Deref, RangeBounds},
    ptr::addr_of,
    slice,
};

use either::Either;
pub(crate) use private::InlinedLayout;

#[cfg(feature = "oom-handling")]
use crate::layout::AnyBufferLayout;
#[cfg(not(feature = "oom-handling"))]
use crate::layout::CloneNoAllocLayout;
use crate::{
    buffer::{Emptyable, Slice, SliceExt, Subsliceable},
    error::AllocError,
    layout::{ArcLayout, BoxedSliceLayout, DefaultLayout, Layout, StaticLayout, VecLayout},
    msrv::ptr,
    utils::{debug_slice, lower_hex, panic_out_of_range, range_offset_len, upper_hex},
    ArcSlice,
};

const INLINED_FLAG: u8 = 0x80;

mod private {
    #[allow(clippy::missing_safety_doc)]
    pub unsafe trait InlinedLayout {
        const LEN: usize;
        type Data: Copy;
        const UNINIT: Self::Data;
    }
}

const _3_WORDS_LEN: usize = 3 * size_of::<usize>() - 2;
const _4_WORDS_LEN: usize = 4 * size_of::<usize>() - 2;

unsafe impl<const ANY_BUFFER: bool, const STATIC: bool> InlinedLayout
    for ArcLayout<ANY_BUFFER, STATIC>
{
    const LEN: usize = _3_WORDS_LEN;
    type Data = [MaybeUninit<u8>; _3_WORDS_LEN];
    const UNINIT: Self::Data = [MaybeUninit::uninit(); _3_WORDS_LEN];
}

unsafe impl InlinedLayout for BoxedSliceLayout {
    const LEN: usize = _3_WORDS_LEN;
    type Data = [MaybeUninit<u8>; _3_WORDS_LEN];
    const UNINIT: Self::Data = [MaybeUninit::uninit(); _3_WORDS_LEN];
}

unsafe impl InlinedLayout for VecLayout {
    const LEN: usize = _4_WORDS_LEN;
    type Data = [MaybeUninit<u8>; _4_WORDS_LEN];
    const UNINIT: Self::Data = [MaybeUninit::uninit(); _4_WORDS_LEN];
}

#[cfg(feature = "raw-buffer")]
unsafe impl InlinedLayout for crate::layout::RawLayout {
    const LEN: usize = _4_WORDS_LEN;
    type Data = [MaybeUninit<u8>; _4_WORDS_LEN];
    const UNINIT: Self::Data = [MaybeUninit::uninit(); _4_WORDS_LEN];
}

/// An inlined storage that can contains a slice up to `size_of::<ArcBytes<L>>() - 2` bytes.
///
/// # Examples
///
/// ```rust
/// use arc_slice::inlined::SmallSlice;
///
/// let s = SmallSlice::<str>::new("hello world").unwrap();
/// assert_eq!(s, "hello world");
#[repr(C)]
pub struct SmallSlice<S: Slice<Item = u8> + ?Sized, L: Layout = DefaultLayout> {
    #[cfg(target_endian = "big")]
    tagged_length: u8,
    data: <L as InlinedLayout>::Data,
    offset: u8,
    #[cfg(target_endian = "little")]
    tagged_length: u8,
    _phantom: PhantomData<S>,
}

impl<S: Slice<Item = u8> + ?Sized, L: Layout> SmallSlice<S, L> {
    const MAX_LEN: usize = L::LEN;

    /// An empty SmallSlice.
    pub const EMPTY: Self = Self {
        data: L::UNINIT,
        offset: 0,
        tagged_length: INLINED_FLAG,
        _phantom: PhantomData,
    };

    /// Create a new `SmallSlice` if the slice fits in.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arc_slice::inlined::SmallSlice;
    ///
    /// assert!(SmallSlice::<[u8]>::new(&[0, 1, 2]).is_some());
    /// assert!(SmallSlice::<[u8]>::new(&[0; 256]).is_none());
    /// ```
    pub fn new(slice: &S) -> Option<Self> {
        if slice.len() > Self::MAX_LEN {
            return None;
        }
        let mut this = Self {
            data: L::UNINIT,
            offset: 0,
            tagged_length: slice.len() as u8 | INLINED_FLAG,
            _phantom: PhantomData,
        };
        let data = ptr::from_mut(&mut this.data).cast::<u8>();
        unsafe { ptr::copy_nonoverlapping(slice.as_ptr().as_ptr(), data, slice.len()) }
        Some(this)
    }

    #[inline(always)]
    const fn is_inlined(this: *const Self) -> bool {
        unsafe { (*addr_of!((*this).tagged_length)) & INLINED_FLAG != 0 }
    }

    /// Returns the number of items in the slice.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arc_slice::inlined::SmallSlice;
    ///
    /// let s = SmallSlice::<[u8]>::new(&[0, 1, 2]).unwrap();
    /// assert_eq!(s.len(), 3);
    /// ```
    pub const fn len(&self) -> usize {
        (self.tagged_length & !INLINED_FLAG) as usize
    }

    /// Returns `true` if the slice contains no items.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arc_slice::inlined::SmallSlice;
    ///
    /// let s = SmallSlice::<[u8]>::new(&[0, 1, 2]).unwrap();
    /// assert!(!s.is_empty());
    ///
    /// let s = SmallSlice::<[u8]>::new(&[]).unwrap();
    /// assert!(s.is_empty());
    /// ```
    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns a raw pointer to the slice's first item.
    ///
    /// See [`slice::as_ptr`].
    pub const fn as_ptr(&self) -> *const u8 {
        let data = ptr::from_ref(&self.data).cast::<u8>();
        unsafe { data.add(self.offset as usize) }
    }

    /// Advances the start of the slice by `offset` items.
    ///
    /// # Panics
    ///
    /// Panics if `offset > self.len()`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arc_slice::inlined::SmallSlice;
    ///
    /// let mut s = SmallSlice::<[u8]>::new(b"hello world").unwrap();
    /// s.advance(6);
    /// assert_eq!(s, b"world");
    /// ```
    pub fn advance(&mut self, offset: usize)
    where
        S: Subsliceable,
    {
        if offset > self.len() {
            panic_out_of_range()
        }
        unsafe { self.check_advance(offset) };
        self.offset += offset as u8;
        self.tagged_length -= offset as u8;
    }

    /// Truncate the slice to the first `len` items.
    ///
    /// If `len` is greater than the slice length, this has no effect.
    ///
    /// ```rust
    /// use arc_slice::inlined::SmallSlice;
    ///
    /// let mut s = SmallSlice::<[u8]>::new(b"hello world").unwrap();
    /// s.truncate(5);
    /// assert_eq!(s, b"hello");
    /// ```
    pub fn truncate(&mut self, len: usize)
    where
        S: Subsliceable,
    {
        if len < self.len() {
            unsafe { self.check_truncate(len) };
            self.tagged_length = len as u8 | INLINED_FLAG;
        }
    }

    /// Extracts a subslice of a `SmallSlice` with a given range.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arc_slice::inlined::SmallSlice;
    ///
    /// let s = SmallSlice::<[u8]>::new(b"hello world").unwrap();
    /// let s2 = s.subslice(..5);
    /// assert_eq!(s2, b"hello");
    /// ```
    pub fn subslice(&self, range: impl RangeBounds<usize>) -> Self
    where
        S: Subsliceable,
    {
        let (offset, len) = range_offset_len(self.deref(), range);
        Self {
            offset: self.offset + offset as u8,
            tagged_length: len as u8 | INLINED_FLAG,
            ..*self
        }
    }
}

impl<S: Slice<Item = u8> + ?Sized, L: Layout> Clone for SmallSlice<S, L> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<S: Slice<Item = u8> + ?Sized, L: Layout> Copy for SmallSlice<S, L> {}

impl<S: Slice<Item = u8> + ?Sized, L: Layout> Deref for SmallSlice<S, L> {
    type Target = S;

    fn deref(&self) -> &Self::Target {
        unsafe { S::from_slice_unchecked(slice::from_raw_parts(self.as_ptr(), self.len())) }
    }
}

impl<S: Slice<Item = u8> + ?Sized, L: Layout> AsRef<S> for SmallSlice<S, L> {
    fn as_ref(&self) -> &S {
        self
    }
}

impl<S: Hash + Slice<Item = u8> + ?Sized, L: Layout> Hash for SmallSlice<S, L> {
    fn hash<H>(&self, state: &mut H)
    where
        H: Hasher,
    {
        self.deref().hash(state);
    }
}

impl<S: Slice<Item = u8> + ?Sized, L: Layout> Borrow<S> for SmallSlice<S, L> {
    fn borrow(&self) -> &S {
        self
    }
}

impl<S: Emptyable<Item = u8> + ?Sized, L: Layout> Default for SmallSlice<S, L> {
    fn default() -> Self {
        Self::EMPTY
    }
}

impl<S: fmt::Debug + Slice<Item = u8> + ?Sized, L: Layout> fmt::Debug for SmallSlice<S, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        debug_slice(self.deref(), f)
    }
}

impl<S: fmt::Display + Slice<Item = u8> + ?Sized, L: Layout> fmt::Display for SmallSlice<S, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.deref().fmt(f)
    }
}

impl<S: Slice<Item = u8> + ?Sized, L: Layout> fmt::LowerHex for SmallSlice<S, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        lower_hex(self.to_slice(), f)
    }
}

impl<S: Slice<Item = u8> + ?Sized, L: Layout> fmt::UpperHex for SmallSlice<S, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        upper_hex(self.to_slice(), f)
    }
}

impl<S: PartialEq + Slice<Item = u8> + ?Sized, L: Layout> PartialEq for SmallSlice<S, L> {
    fn eq(&self, other: &SmallSlice<S, L>) -> bool {
        **self == **other
    }
}

impl<S: PartialEq + Slice<Item = u8> + ?Sized, L: Layout> Eq for SmallSlice<S, L> {}

impl<S: PartialOrd + Slice<Item = u8> + ?Sized, L: Layout> PartialOrd for SmallSlice<S, L> {
    fn partial_cmp(&self, other: &SmallSlice<S, L>) -> Option<cmp::Ordering> {
        self.deref().partial_cmp(other.deref())
    }
}

impl<S: Ord + Slice<Item = u8> + ?Sized, L: Layout> Ord for SmallSlice<S, L> {
    fn cmp(&self, other: &SmallSlice<S, L>) -> cmp::Ordering {
        self.deref().cmp(other.deref())
    }
}

impl<S: PartialEq + Slice<Item = u8> + ?Sized, L: Layout> PartialEq<S> for SmallSlice<S, L> {
    fn eq(&self, other: &S) -> bool {
        self.deref() == other
    }
}

impl<'a, S: PartialEq + Slice<Item = u8> + ?Sized, L: Layout> PartialEq<&'a S>
    for SmallSlice<S, L>
{
    fn eq(&self, other: &&'a S) -> bool {
        self.deref() == *other
    }
}

impl<L: Layout, const N: usize> PartialEq<[u8; N]> for SmallSlice<[u8], L> {
    fn eq(&self, other: &[u8; N]) -> bool {
        *other == **self
    }
}

impl<'a, L: Layout, const N: usize> PartialEq<&'a [u8; N]> for SmallSlice<[u8], L> {
    fn eq(&self, other: &&'a [u8; N]) -> bool {
        **other == **self
    }
}

impl<L: Layout, const N: usize> PartialEq<SmallSlice<[u8], L>> for [u8; N] {
    fn eq(&self, other: &SmallSlice<[u8], L>) -> bool {
        **other == *self
    }
}

impl<L: Layout> PartialEq<SmallSlice<[u8], L>> for [u8] {
    fn eq(&self, other: &SmallSlice<[u8], L>) -> bool {
        **other == *self
    }
}

impl<L: Layout> PartialEq<SmallSlice<str, L>> for str {
    fn eq(&self, other: &SmallSlice<str, L>) -> bool {
        **other == *self
    }
}

impl<L: Layout> PartialEq<Vec<u8>> for SmallSlice<[u8], L> {
    fn eq(&self, other: &Vec<u8>) -> bool {
        **self == **other
    }
}

impl<L: Layout> PartialEq<String> for SmallSlice<str, L> {
    fn eq(&self, other: &String) -> bool {
        **self == **other
    }
}

impl<L: Layout> PartialEq<SmallSlice<[u8], L>> for Vec<u8> {
    fn eq(&self, other: &SmallSlice<[u8], L>) -> bool {
        **self == **other
    }
}

impl<L: Layout> PartialEq<SmallSlice<str, L>> for String {
    fn eq(&self, other: &SmallSlice<str, L>) -> bool {
        **self == **other
    }
}

/// A wrapper enabling [small string optimization] into [`ArcSlice`].
///
/// It can store up to `size_of::<ArcBytes<L>>() - 2` bytes inline, without allocating.
/// However, the niche optimization of `ArcSlice` is lost, which means that
/// `size_of::<Option<SmallArcBytes<L>>>() == size_of::<SmallArcBytes<L>>() + size_of::<usize>()`.
///
/// [small string optimization]: https://cppdepend.com/blog/understanding-small-string-optimization-sso-in-stdstring/
pub struct SmallArcSlice<S: Slice<Item = u8> + ?Sized, L: Layout = DefaultLayout>(Inner<S, L>);

#[repr(C)]
union Inner<S: Slice<Item = u8> + ?Sized, L: Layout> {
    small: SmallSlice<S, L>,
    arc: ManuallyDrop<ArcSlice<S, L>>,
}

impl<S: Slice<Item = u8> + ?Sized, L: Layout> SmallArcSlice<S, L> {
    /// Creates a new empty `SmallArcSlice`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arc_slice::inlined::SmallArcSlice;
    ///
    /// let s = SmallArcSlice::<[u8]>::new();
    /// assert_eq!(s, []);
    /// ```
    pub const fn new() -> Self {
        Self(Inner {
            small: SmallSlice::EMPTY,
        })
    }

    /// Creates a new `SmallArcSlice` by copying the given slice.
    ///
    /// The slice will be stored inlined if it can fit into a `SmallSlice`.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity exceeds `isize::MAX - size_of::<usize>()` bytes.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arc_slice::inlined::SmallArcSlice;
    ///
    /// let s = SmallArcSlice::<[u8]>::from_slice(b"hello world");
    /// assert_eq!(s, b"hello world");
    /// ```
    #[cfg(feature = "oom-handling")]
    pub fn from_slice(slice: &S) -> Self {
        SmallSlice::new(slice).map_or_else(|| ArcSlice::from_slice(slice).into(), Into::into)
    }

    /// Tries creating a new `SmallArcSlice` by copying the given slice, returning an error if the
    /// allocation fails.
    ///
    /// The slice will be stored inlined if it can fit into a `SmallSlice`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arc_slice::inlined::SmallArcSlice;
    ///
    /// # fn main() -> Result<(), arc_slice::error::AllocError> {
    /// let s = SmallArcSlice::<[u8]>::try_from_slice(b"hello world")?;
    /// assert_eq!(s, b"hello world");
    /// # Ok(())
    /// # }
    /// ```
    pub fn try_from_slice(slice: &S) -> Result<Self, AllocError> {
        SmallSlice::new(slice).map_or_else(
            || Ok(ArcSlice::try_from_slice(slice)?.into()),
            |s| Ok(s.into()),
        )
    }

    /// Returns either a reference to the inlined [`SmallSlice`] storage, or to the [`ArcSlice`]
    /// one.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arc_slice::inlined::SmallArcSlice;
    /// use either::Either;
    ///
    /// let s = SmallArcSlice::<[u8]>::new();
    /// assert!(matches!(s.as_either(), Either::Left(_)));
    ///
    /// let s = SmallArcSlice::<[u8]>::from_array([0; 256]);
    /// assert!(matches!(s.as_either(), Either::Right(_)));
    /// ```
    #[inline(always)]
    pub fn as_either(&self) -> Either<&SmallSlice<S, L>, &ArcSlice<S, L>> {
        if unsafe { SmallSlice::is_inlined(addr_of!(self.0.small)) } {
            Either::Left(unsafe { &self.0.small })
        } else {
            Either::Right(unsafe { &*ptr::from_ref(&self.0.arc).cast() })
        }
    }

    /// Returns either a mutable reference to the inlined [`SmallSlice`] storage, or to the
    /// [`ArcSlice`] one.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arc_slice::inlined::SmallArcSlice;
    /// use either::Either;
    ///
    /// let mut s = SmallArcSlice::<[u8]>::new();
    /// assert!(matches!(s.as_either_mut(), Either::Left(_)));
    ///
    /// let mut s = SmallArcSlice::<[u8]>::from_array([0; 256]);
    /// assert!(matches!(s.as_either_mut(), Either::Right(_)));
    /// ```
    #[inline(always)]
    pub fn as_either_mut(&mut self) -> Either<&mut SmallSlice<S, L>, &mut ArcSlice<S, L>> {
        if unsafe { SmallSlice::is_inlined(addr_of!(self.0.small)) } {
            Either::Left(unsafe { &mut self.0.small })
        } else {
            Either::Right(unsafe { &mut self.0.arc })
        }
    }

    /// Returns either the inlined [`SmallSlice`] storage, or the [`ArcSlice`] one.
    #[inline(always)]
    pub fn into_either(self) -> Either<SmallSlice<S, L>, ArcSlice<S, L>> {
        let mut this = ManuallyDrop::new(self);
        if unsafe { SmallSlice::is_inlined(addr_of!(this.0.small)) } {
            Either::Left(unsafe { this.0.small })
        } else {
            Either::Right(unsafe { ManuallyDrop::take(&mut this.0.arc) })
        }
    }

    /// Returns the number of items in the slice.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arc_slice::inlined::SmallArcSlice;
    ///
    /// let s = SmallArcSlice::<[u8]>::from(&[0, 1, 2]);
    /// assert_eq!(s.len(), 3);
    /// ```
    pub fn len(&self) -> usize {
        match self.as_either() {
            Either::Left(bytes) => bytes.len(),
            Either::Right(bytes) => bytes.len(),
        }
    }

    /// Returns `true` if the slice contains no items.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arc_slice::inlined::SmallArcSlice;
    ///
    /// let s = SmallArcSlice::<[u8]>::from(&[0, 1, 2]);
    /// assert!(!s.is_empty());
    ///
    /// let s = SmallArcSlice::<[u8]>::from(&[]);
    /// assert!(s.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns a raw pointer to the slice's first item.
    ///
    /// See [`slice::as_ptr`].
    pub fn as_ptr(&self) -> *const u8 {
        match self.as_either() {
            Either::Left(bytes) => bytes.as_ptr(),
            Either::Right(bytes) => bytes.start.as_ptr(),
        }
    }

    /// Tries cloning the `SmallArcSlice`, returning an error if an allocation fails.
    ///
    /// The operation may allocate. See [`CloneNoAllocLayout`](crate::layout::CloneNoAllocLayout)
    /// documentation for cases where it does not.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arc_slice::inlined::SmallArcSlice;
    ///
    /// # fn main() -> Result<(), arc_slice::error::AllocError> {
    /// let s = SmallArcSlice::<[u8]>::try_from_slice(b"hello world")?;
    /// let s2 = s.try_clone()?;
    /// assert_eq!(s2, b"hello world");
    /// # Ok(())
    /// # }
    /// ```
    pub fn try_clone(&self) -> Result<Self, AllocError> {
        Ok(match self.as_either() {
            Either::Left(bytes) => Self(Inner { small: *bytes }),
            Either::Right(bytes) => Self(Inner {
                arc: ManuallyDrop::new(bytes.try_clone()?),
            }),
        })
    }

    /// Tries extracting a subslice of an `SmallArcSlice` with a given range, returning an error
    /// if an allocation fails.
    ///
    /// The operation may allocate. See [`CloneNoAllocLayout`](crate::layout::CloneNoAllocLayout)
    /// documentation for cases where it does not.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arc_slice::inlined::SmallArcSlice;
    ///
    /// # fn main() -> Result<(), arc_slice::error::AllocError> {
    /// let s = SmallArcSlice::<[u8]>::try_from_slice(b"hello world")?;
    /// let s2 = s.try_subslice(..5)?;
    /// assert_eq!(s2, b"hello");
    /// # Ok(())
    /// # }
    /// ```
    pub fn try_subslice(&self, range: impl RangeBounds<usize>) -> Result<Self, AllocError>
    where
        S: Subsliceable,
    {
        match self.as_either() {
            Either::Left(bytes) => Ok(bytes.subslice(range).into()),
            Either::Right(bytes) => Ok(bytes.try_subslice(range)?.into()),
        }
    }

    #[doc(hidden)]
    pub fn _advance(&mut self, cnt: usize)
    where
        S: Subsliceable,
    {
        match self.as_either_mut() {
            Either::Left(s) => s.advance(cnt),
            Either::Right(s) => s.advance(cnt),
        }
    }
}

impl<L: Layout> SmallArcSlice<[u8], L> {
    /// Creates a new `SmallArcSlice` by moving the given array.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity exceeds `isize::MAX - size_of::<usize>()` bytes.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arc_slice::inlined::SmallArcSlice;
    ///
    /// let s = SmallArcSlice::<[u8]>::from_array([0, 1, 2]);
    /// assert_eq!(s, [0, 1, 2]);
    /// ```
    #[cfg(feature = "oom-handling")]
    pub fn from_array<const N: usize>(array: [u8; N]) -> Self {
        SmallSlice::new(array.as_slice())
            .map_or_else(|| ArcSlice::from_array(array).into(), Into::into)
    }

    /// Tries creating a new `SmallArcSlice` by moving the given array, returning it if an
    /// allocation fails.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arc_slice::inlined::SmallArcSlice;
    ///
    /// let s = SmallArcSlice::<[u8]>::try_from_array([0, 1, 2]).unwrap();
    /// assert_eq!(s, [0, 1, 2]);
    /// ```
    pub fn try_from_array<const N: usize>(array: [u8; N]) -> Result<Self, [u8; N]> {
        SmallSlice::new(array.as_slice()).map_or_else(
            || Ok(ArcSlice::try_from_array(array)?.into()),
            |a| Ok(a.into()),
        )
    }
}

impl<
        S: Slice<Item = u8> + ?Sized,
        #[cfg(feature = "oom-handling")] L: Layout,
        #[cfg(not(feature = "oom-handling"))] L: CloneNoAllocLayout,
    > SmallArcSlice<S, L>
{
    /// Extracts a subslice of an `SmallArcSlice` with a given range.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arc_slice::inlined::SmallArcSlice;
    ///
    /// let s = SmallArcSlice::<[u8]>::from_slice(b"hello world");
    /// let s2 = s.subslice(..5);
    /// assert_eq!(s2, b"hello");
    /// ```
    pub fn subslice(&self, range: impl RangeBounds<usize>) -> Self
    where
        S: Subsliceable,
    {
        match self.as_either() {
            Either::Left(bytes) => bytes.subslice(range).into(),
            Either::Right(bytes) => bytes.subslice(range).into(),
        }
    }
}

impl<L: StaticLayout> SmallArcSlice<[u8], L> {
    /// Creates a new `SmallArcSlice` from a static slice.
    ///
    /// The operation never allocates.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arc_slice::{inlined::SmallArcSlice, layout::ArcLayout};
    ///
    /// static HELLO_WORLD: SmallArcSlice<[u8], ArcLayout<true, true>> =
    ///     SmallArcSlice::<[u8], ArcLayout<true, true>>::from_static(b"hello world");
    /// ```
    pub const fn from_static(slice: &'static [u8]) -> SmallArcSlice<[u8], L> {
        Self(Inner {
            arc: ManuallyDrop::new(ArcSlice::<[u8], L>::from_static(slice)),
        })
    }
}

impl<L: StaticLayout> SmallArcSlice<str, L> {
    /// Creates a new `SmallArcSlice` from a static slice.
    ///
    /// The operation never allocates.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use arc_slice::{inlined::SmallArcSlice, layout::ArcLayout};
    ///
    /// static HELLO_WORLD: SmallArcSlice<[u8], ArcLayout<true, true>> =
    ///     SmallArcSlice::<[u8], ArcLayout<true, true>>::from_static(b"hello world");
    /// ```
    pub const fn from_static(slice: &'static str) -> SmallArcSlice<str, L> {
        Self(Inner {
            arc: ManuallyDrop::new(ArcSlice::<str, L>::from_static(slice)),
        })
    }
}

impl<S: Slice<Item = u8> + ?Sized, L: Layout> Drop for SmallArcSlice<S, L> {
    fn drop(&mut self) {
        if let Either::Right(bytes) = self.as_either_mut() {
            unsafe { ptr::drop_in_place(bytes) }
        }
    }
}

impl<
        S: Slice<Item = u8> + ?Sized,
        #[cfg(feature = "oom-handling")] L: Layout,
        #[cfg(not(feature = "oom-handling"))] L: CloneNoAllocLayout,
    > Clone for SmallArcSlice<S, L>
{
    fn clone(&self) -> Self {
        match self.as_either() {
            Either::Left(bytes) => Self(Inner { small: *bytes }),
            Either::Right(bytes) => Self(Inner {
                arc: ManuallyDrop::new(bytes.clone()),
            }),
        }
    }
}

impl<S: Slice<Item = u8> + ?Sized, L: Layout> Deref for SmallArcSlice<S, L> {
    type Target = S;

    fn deref(&self) -> &Self::Target {
        match self.as_either() {
            Either::Left(bytes) => bytes,
            Either::Right(bytes) => bytes,
        }
    }
}

impl<S: Slice<Item = u8> + ?Sized, L: Layout> AsRef<S> for SmallArcSlice<S, L> {
    fn as_ref(&self) -> &S {
        self
    }
}

impl<S: Hash + Slice<Item = u8> + ?Sized, L: Layout> Hash for SmallArcSlice<S, L> {
    fn hash<H>(&self, state: &mut H)
    where
        H: Hasher,
    {
        self.deref().hash(state);
    }
}

impl<S: Slice<Item = u8> + ?Sized, L: Layout> Borrow<S> for SmallArcSlice<S, L> {
    fn borrow(&self) -> &S {
        self
    }
}

impl<S: Emptyable<Item = u8> + ?Sized, L: Layout> Default for SmallArcSlice<S, L> {
    fn default() -> Self {
        Self::from(SmallSlice::default())
    }
}

impl<S: fmt::Debug + Slice<Item = u8> + ?Sized, L: Layout> fmt::Debug for SmallArcSlice<S, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        debug_slice(self.deref(), f)
    }
}

impl<S: fmt::Display + Slice<Item = u8> + ?Sized, L: Layout> fmt::Display for SmallArcSlice<S, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.deref().fmt(f)
    }
}

impl<S: Slice<Item = u8> + ?Sized, L: Layout> fmt::LowerHex for SmallArcSlice<S, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        lower_hex(self.to_slice(), f)
    }
}

impl<S: Slice<Item = u8> + ?Sized, L: Layout> fmt::UpperHex for SmallArcSlice<S, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        upper_hex(self.to_slice(), f)
    }
}

impl<S: PartialEq + Slice<Item = u8> + ?Sized, L: Layout> PartialEq for SmallArcSlice<S, L> {
    fn eq(&self, other: &SmallArcSlice<S, L>) -> bool {
        **self == **other
    }
}

impl<S: PartialEq + Slice<Item = u8> + ?Sized, L: Layout> Eq for SmallArcSlice<S, L> {}

impl<S: PartialOrd + Slice<Item = u8> + ?Sized, L: Layout> PartialOrd for SmallArcSlice<S, L> {
    fn partial_cmp(&self, other: &SmallArcSlice<S, L>) -> Option<cmp::Ordering> {
        self.deref().partial_cmp(other.deref())
    }
}

impl<S: Ord + Slice<Item = u8> + ?Sized, L: Layout> Ord for SmallArcSlice<S, L> {
    fn cmp(&self, other: &SmallArcSlice<S, L>) -> cmp::Ordering {
        self.deref().cmp(other.deref())
    }
}

impl<S: PartialEq + Slice<Item = u8> + ?Sized, L: Layout> PartialEq<S> for SmallArcSlice<S, L> {
    fn eq(&self, other: &S) -> bool {
        self.deref() == other
    }
}

impl<'a, S: PartialEq + Slice<Item = u8> + ?Sized, L: Layout> PartialEq<&'a S>
    for SmallArcSlice<S, L>
{
    fn eq(&self, other: &&'a S) -> bool {
        self.deref() == *other
    }
}

impl<L: Layout, const N: usize> PartialEq<[u8; N]> for SmallArcSlice<[u8], L> {
    fn eq(&self, other: &[u8; N]) -> bool {
        *other == **self
    }
}

impl<'a, L: Layout, const N: usize> PartialEq<&'a [u8; N]> for SmallArcSlice<[u8], L> {
    fn eq(&self, other: &&'a [u8; N]) -> bool {
        **other == **self
    }
}

impl<L: Layout, const N: usize> PartialEq<SmallArcSlice<[u8], L>> for [u8; N] {
    fn eq(&self, other: &SmallArcSlice<[u8], L>) -> bool {
        **other == *self
    }
}

impl<L: Layout> PartialEq<SmallArcSlice<[u8], L>> for [u8] {
    fn eq(&self, other: &SmallArcSlice<[u8], L>) -> bool {
        **other == *self
    }
}

impl<L: Layout> PartialEq<SmallArcSlice<str, L>> for str {
    fn eq(&self, other: &SmallArcSlice<str, L>) -> bool {
        **other == *self
    }
}

impl<L: Layout> PartialEq<Vec<u8>> for SmallArcSlice<[u8], L> {
    fn eq(&self, other: &Vec<u8>) -> bool {
        **self == **other
    }
}

impl<L: Layout> PartialEq<String> for SmallArcSlice<str, L> {
    fn eq(&self, other: &String) -> bool {
        **self == **other
    }
}

impl<L: Layout> PartialEq<SmallArcSlice<[u8], L>> for Vec<u8> {
    fn eq(&self, other: &SmallArcSlice<[u8], L>) -> bool {
        **self == **other
    }
}

impl<L: Layout> PartialEq<SmallArcSlice<str, L>> for String {
    fn eq(&self, other: &SmallArcSlice<str, L>) -> bool {
        **self == **other
    }
}

#[cfg(feature = "oom-handling")]
impl<S: Slice<Item = u8> + ?Sized, L: AnyBufferLayout> From<&S> for SmallArcSlice<S, L> {
    fn from(value: &S) -> Self {
        Self::from_slice(value)
    }
}

#[cfg(feature = "oom-handling")]
impl<L: AnyBufferLayout, const N: usize> From<&[u8; N]> for SmallArcSlice<[u8], L> {
    fn from(value: &[u8; N]) -> Self {
        Self::from_slice(value)
    }
}

#[cfg(feature = "oom-handling")]
impl<L: AnyBufferLayout, const N: usize> From<[u8; N]> for SmallArcSlice<[u8], L> {
    fn from(value: [u8; N]) -> Self {
        Self::from_array(value)
    }
}

#[cfg(feature = "oom-handling")]
impl<S: Slice<Item = u8> + ?Sized, L: AnyBufferLayout> From<alloc::boxed::Box<S>>
    for SmallArcSlice<S, L>
{
    fn from(value: alloc::boxed::Box<S>) -> Self {
        ArcSlice::from(value).into()
    }
}

#[cfg(feature = "oom-handling")]
impl<L: AnyBufferLayout> From<Vec<u8>> for SmallArcSlice<[u8], L> {
    fn from(value: Vec<u8>) -> Self {
        ArcSlice::from(value).into()
    }
}

#[cfg(feature = "oom-handling")]
impl<L: AnyBufferLayout> From<String> for SmallArcSlice<str, L> {
    fn from(value: String) -> Self {
        ArcSlice::from(value).into()
    }
}

impl<S: Slice<Item = u8> + ?Sized, L: Layout> From<SmallSlice<S, L>> for SmallArcSlice<S, L> {
    fn from(value: SmallSlice<S, L>) -> Self {
        Self(Inner { small: value })
    }
}

impl<S: Slice<Item = u8> + ?Sized, L: Layout> From<ArcSlice<S, L>> for SmallArcSlice<S, L> {
    fn from(value: ArcSlice<S, L>) -> Self {
        Self(Inner {
            arc: ManuallyDrop::new(value),
        })
    }
}

#[cfg(feature = "oom-handling")]
impl<L: Layout> core::str::FromStr for SmallArcSlice<str, L> {
    type Err = core::convert::Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self::from_slice(s))
    }
}

/// An alias for `SmallArcSlice<[u8], L>`.
pub type SmallArcBytes<L = DefaultLayout> = SmallArcSlice<[u8], L>;
/// An alias for `SmallArcSlice<str, L>`.
pub type SmallArcStr<L = DefaultLayout> = SmallArcSlice<str, L>;