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
use core::cmp::Ordering;
use core::hash::Hash;
use core::marker::PhantomData;
use core::mem::size_of;
use core::{any, fmt};

use crate::endian::{Big, ByteOrder, Little, Native};
use crate::error::{Error, ErrorKind, IntoRepr};
use crate::mem::MaybeUninit;
use crate::pointer::Coerce;
use crate::pointer::{DefaultSize, Packable, Pointee, Size};
use crate::ZeroCopy;

/// A stored reference to a type `T`.
///
/// A reference is made up of two components:
/// * An [`offset()`] indicating the absolute offset into a [`Buf`] where the
///   pointed-to (pointee) data is located.
/// * An optional [`metadata()`] components, which if set indicates that this
///   reference is a wide pointer. This is used when encoding types such as
///   `[T]` or `str` to include additional data necessary to handle the type.
///
/// [`Buf`]: crate::buf::Buf
/// [`offset()`]: Ref::offset
/// [`metadata()`]: Ref::metadata
///
/// # Examples
///
/// ```
/// use std::mem::align_of;
///
/// use musli_zerocopy::{Ref, OwnedBuf};
///
/// let mut buf = OwnedBuf::with_alignment::<u32>();
/// buf.extend_from_slice(&[1, 2, 3, 4]);
///
/// let buf = buf.as_ref();
///
/// let number = Ref::<u32>::new(0);
/// assert_eq!(*buf.load(number)?, u32::from_ne_bytes([1, 2, 3, 4]));
/// # Ok::<_, musli_zerocopy::Error>(())
/// ```
#[derive(ZeroCopy)]
#[repr(C)]
#[zero_copy(crate, swap_bytes, bounds = {<T::Metadata as Packable>::Packed<O>: ZeroCopy})]
pub struct Ref<T: ?Sized, E: ByteOrder = Native, O: Size = DefaultSize>
where
    T: Pointee,
{
    offset: O,
    metadata: <T::Metadata as Packable>::Packed<O>,
    #[zero_copy(ignore)]
    _marker: PhantomData<(E, T)>,
}

impl<T: ?Sized, E: ByteOrder, O: Size> Ref<T, E, O>
where
    T: Pointee,
{
    /// Convert this reference into a [`Big`]-endian [`ByteOrder`].
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::{endian, Ref};
    ///
    /// let r: Ref<u32> = Ref::new(10);
    /// assert_eq!(r.offset(), 10);
    ///
    /// let r: Ref<u32, endian::Little> = Ref::new(10);
    /// assert_eq!(r.offset(), 10);
    ///
    /// let r: Ref<u32, endian::Big> = r.to_be();
    /// assert_eq!(r.offset(), 10);
    /// ```
    #[inline]
    pub fn to_be(self) -> Ref<T, Big, O> {
        self.to_endian()
    }

    /// Convert this reference into a [`Little`]-endian [`ByteOrder`].
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::{endian, Ref};
    ///
    /// let r: Ref<u32> = Ref::new(10);
    /// assert_eq!(r.offset(), 10);
    ///
    /// let r: Ref<u32, endian::Big> = Ref::new(10);
    /// assert_eq!(r.offset(), 10);
    ///
    /// let r: Ref<u32, endian::Little> = r.to_le();
    /// assert_eq!(r.offset(), 10);
    /// ```
    #[inline]
    pub fn to_le(self) -> Ref<T, Little, O> {
        self.to_endian()
    }

    /// Convert this reference into a [`Native`]-endian [`ByteOrder`].
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::{endian, Ref};
    ///
    /// let r: Ref<u32, endian::Native> = Ref::<u32, endian::Big>::new(10).to_ne();
    /// assert_eq!(r.offset(), 10);
    ///
    /// let r: Ref<u32, endian::Native> = Ref::<u32, endian::Little>::new(10).to_ne();
    /// assert_eq!(r.offset(), 10);
    ///
    /// let r: Ref<u32, endian::Native> = Ref::<u32, endian::Native>::new(10).to_ne();
    /// assert_eq!(r.offset(), 10);
    /// ```
    #[inline]
    pub fn to_ne(self) -> Ref<T, Native, O> {
        self.to_endian()
    }

    /// Convert this reference into a `U`-endian [`ByteOrder`].
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::{endian, Ref};
    ///
    /// let r: Ref<u32, endian::Native> = Ref::<u32, endian::Big>::new(10).to_endian();
    /// assert_eq!(r.offset(), 10);
    ///
    /// let r: Ref<u32, endian::Native> = Ref::<u32, endian::Little>::new(10).to_endian();
    /// assert_eq!(r.offset(), 10);
    ///
    /// let r: Ref<u32, endian::Native> = Ref::<u32, endian::Native>::new(10).to_endian();
    /// assert_eq!(r.offset(), 10);
    /// ```
    #[inline]
    pub fn to_endian<U: ByteOrder>(self) -> Ref<T, U, O> {
        Ref {
            offset: self.offset.transpose_bytes::<E, U>(),
            metadata: self.metadata.transpose_bytes::<E, U>(),
            _marker: PhantomData,
        }
    }
}

impl<T: ?Sized, E: ByteOrder, O: Size> Ref<T, E, O>
where
    T: Pointee,
{
    /// Construct a reference with custom metadata.
    ///
    /// # Panics
    ///
    /// This will panic if either:
    /// * The `offset` or `metadata` can't be byte swapped as per
    ///   [`ZeroCopy::CAN_SWAP_BYTES`].
    /// * Packed [`offset()`] cannot be constructed from `U` (out of range).
    /// * Packed [`metadata()`] cannot be constructed from `T::Metadata` (reason
    ///   depends on the exact metadata).
    ///
    /// To guarantee that this constructor will never panic, [`Ref<T, E,
    /// usize>`] can be used. This also ensures that construction is a no-op.
    ///
    /// [`offset()`]: Ref::offset
    /// [`metadata()`]: Ref::metadata
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::Ref;
    ///
    /// let reference = Ref::<[u64]>::with_metadata(42, 10);
    /// assert_eq!(reference.offset(), 42);
    /// assert_eq!(reference.len(), 10);
    /// ```
    #[inline]
    pub fn with_metadata<U>(offset: U, metadata: T::Metadata) -> Self
    where
        U: Copy + fmt::Debug,
        O: TryFrom<U>,
    {
        assert!(
            O::CAN_SWAP_BYTES,
            "Offset `{}` cannot be byte-ordered since it would not inhabit valid types",
            any::type_name::<O>()
        );

        let Some(offset) = O::try_from(offset).ok() else {
            panic!("Offset {offset:?} not in legal range 0-{}", O::MAX);
        };

        let Some(metadata) = <T::Metadata as Packable>::try_from_metadata(metadata) else {
            panic!("Metadata {metadata:?} not in legal range 0-{}", O::MAX);
        };

        Self {
            offset: O::swap_bytes::<E>(offset),
            metadata: <T::Metadata as Packable>::Packed::<O>::swap_bytes::<E>(metadata),
            _marker: PhantomData,
        }
    }

    /// Fallibly try to construct a reference with metadata.
    ///
    /// # Errors
    ///
    /// This will error if either:
    /// * The `offset` or `metadata` can't be byte swapped as per
    ///   [`ZeroCopy::CAN_SWAP_BYTES`].
    /// * Packed [`offset()`] cannot be constructed from `U` (out of range).
    /// * Packed [`metadata()`] cannot be constructed from `T::Metadata` (reason
    ///   depends on the exact metadata).
    ///
    /// To guarantee that this constructor will never error, [`Ref<T, Native,
    /// usize>`] can be used. This also ensures that construction is a no-op.
    ///
    /// [`offset()`]: Ref::offset
    /// [`metadata()`]: Ref::metadata
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::Ref;
    ///
    /// let reference = Ref::<[u64]>::try_with_metadata(42, 10)?;
    /// assert_eq!(reference.offset(), 42);
    /// assert_eq!(reference.len(), 10);
    /// # Ok::<_, musli_zerocopy::Error>(())
    /// ```
    pub fn try_with_metadata<U>(offset: U, metadata: T::Metadata) -> Result<Self, Error>
    where
        U: Copy + IntoRepr + fmt::Debug,
        O: TryFrom<U>,
    {
        if !O::CAN_SWAP_BYTES {
            return Err(Error::new(ErrorKind::InvalidOffset {
                ty: any::type_name::<O>(),
            }));
        }

        if !<T::Metadata as Packable>::Packed::<O>::CAN_SWAP_BYTES {
            return Err(Error::new(ErrorKind::InvalidMetadata {
                ty: any::type_name::<T::Metadata>(),
                packed: any::type_name::<<T::Metadata as Packable>::Packed<O>>(),
            }));
        }

        let Some(offset) = O::try_from(offset).ok() else {
            return Err(Error::new(ErrorKind::InvalidOffsetRange {
                offset: U::into_repr(offset),
                max: O::into_repr(O::MAX),
            }));
        };

        let Some(metadata) = <T::Metadata as Packable>::try_from_metadata(metadata) else {
            return Err(Error::new(ErrorKind::InvalidMetadataRange {
                metadata: T::Metadata::into_repr(metadata),
                max: O::into_repr(O::MAX),
            }));
        };

        Ok(Self {
            offset: O::swap_bytes::<E>(offset),
            metadata: <T::Metadata as Packable>::Packed::<O>::swap_bytes::<E>(metadata),
            _marker: PhantomData,
        })
    }
}

impl<T, E: ByteOrder, O: Size> Ref<[T], E, O>
where
    T: ZeroCopy,
{
    /// Return the number of elements in the slice `[T]`.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::pointer::Ref;
    ///
    /// let slice = Ref::<[u32]>::with_metadata(0, 2);
    /// assert_eq!(slice.len(), 2);
    /// ```
    #[inline]
    pub fn len(self) -> usize {
        self.metadata.as_usize::<E>()
    }

    /// Test if the slice `[T]` is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::pointer::Ref;
    ///
    /// let slice = Ref::<[u32]>::with_metadata(0, 0);
    /// assert!(slice.is_empty());
    ///
    /// let slice = Ref::<[u32]>::with_metadata(0, 2);
    /// assert!(!slice.is_empty());
    /// ```
    #[inline]
    pub fn is_empty(self) -> bool {
        self.metadata.is_zero()
    }

    /// Try to get a reference directly out of the slice without validation.
    ///
    /// This avoids having to validate every element in a slice in order to
    /// address them.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::OwnedBuf;
    ///
    /// let mut buf = OwnedBuf::new();
    /// let slice = buf.store_slice(&[1, 2, 3, 4]);
    ///
    /// let two = slice.get(2).expect("Missing element 2");
    /// assert_eq!(buf.load(two)?, &3);
    ///
    /// assert!(slice.get(4).is_none());
    /// # Ok::<_, musli_zerocopy::Error>(())
    /// ```
    #[inline]
    pub fn get(self, index: usize) -> Option<Ref<T, E, O>> {
        if index >= self.len() {
            return None;
        }

        let offset = self.offset.as_usize::<E>() + size_of::<T>() * index;
        Some(Ref::new(offset))
    }

    /// Get an unchecked reference directly out of the slice without validation.
    ///
    /// This avoids having to validate every element in a slice in order to
    /// address them.
    ///
    /// In contrast to [`get()`], this does not check that the index is within
    /// the bounds of the current slice, all though it's not unsafe since it
    /// cannot lead to anything inherently unsafe. Only garbled data.
    ///
    /// [`get()`]: Ref::get
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::OwnedBuf;
    ///
    /// let mut buf = OwnedBuf::new();
    /// let slice = buf.store_slice(&[1, 2, 3, 4]);
    ///
    /// let two = slice.get_unchecked(2);
    /// assert_eq!(buf.load(two)?, &3);
    ///
    /// let oob = slice.get_unchecked(4);
    /// assert!(buf.load(oob).is_err());
    /// # Ok::<_, musli_zerocopy::Error>(())
    /// ```
    pub fn get_unchecked(self, index: usize) -> Ref<T, E, O> {
        let offset = self.offset.as_usize::<E>() + size_of::<T>() * index;
        Ref::new(offset)
    }

    /// Split the slice reference at the given position `at`.
    ///
    /// # Panics
    ///
    /// This panics if the given range is out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::OwnedBuf;
    ///
    /// let mut buf = OwnedBuf::new();
    /// let slice = buf.store_slice(&[1, 2, 3, 4]);
    ///
    /// buf.align_in_place();
    ///
    /// let (a, b) = slice.split_at(3);
    /// let (c, d) = slice.split_at(4);
    ///
    /// assert_eq!(buf.load(a)?, &[1, 2, 3]);
    /// assert_eq!(buf.load(b)?, &[4]);
    /// assert_eq!(buf.load(c)?, &[1, 2, 3, 4]);
    /// assert_eq!(buf.load(d)?, &[]);
    /// # Ok::<_, musli_zerocopy::Error>(())
    /// ```
    #[inline]
    pub fn split_at(self, at: usize) -> (Self, Self) {
        let offset = self.offset();
        let len = self.len();
        assert!(at <= len, "Split point {at} is out of bounds 0..={len}");
        let a = Self::with_metadata(offset, at);
        let b = Self::with_metadata(offset + at * size_of::<T>(), len - at);
        (a, b)
    }

    /// Perform an fetch like `get` which panics with diagnostics in case the
    /// index is out-of-bounds.
    #[inline]
    #[cfg(feature = "alloc")]
    pub(crate) fn at(self, index: usize) -> Ref<T, E, O> {
        let Some(r) = self.get(index) else {
            panic!("Index {index} out of bounds 0-{}", self.len());
        };

        r
    }

    /// Construct an iterator over this reference.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::OwnedBuf;
    ///
    /// let mut buf = OwnedBuf::new();
    /// buf.extend_from_slice(&[1, 2, 3, 4]);
    ///
    /// let slice = buf.store_slice(&[1, 2, 3, 4]);
    ///
    /// buf.align_in_place();
    ///
    /// let mut out = Vec::new();
    ///
    /// for r in slice.iter() {
    ///     out.push(*buf.load(r)?);
    /// }
    ///
    /// for r in slice.iter().rev() {
    ///     out.push(*buf.load(r)?);
    /// }
    ///
    /// assert_eq!(out, [1, 2, 3, 4, 4, 3, 2, 1]);
    /// # Ok::<_, musli_zerocopy::Error>(())
    /// ```
    #[inline]
    pub fn iter(self) -> Iter<T, E, O> {
        let start = self.offset.as_usize::<E>();
        let end = start + self.metadata.as_usize::<E>() * size_of::<T>();

        Iter {
            start,
            end,
            _marker: PhantomData,
        }
    }
}

impl<E: ByteOrder, O: Size> Ref<str, E, O> {
    /// Return the length of the string.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::pointer::Ref;
    ///
    /// let slice = Ref::<str>::with_metadata(0, 2);
    /// assert_eq!(slice.len(), 2);
    /// ```
    #[inline]
    pub fn len(self) -> usize {
        self.metadata.as_usize::<E>()
    }

    /// Test if the slice `[T]` is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::pointer::Ref;
    ///
    /// let slice = Ref::<str>::with_metadata(0, 0);
    /// assert!(slice.is_empty());
    ///
    /// let slice = Ref::<str>::with_metadata(0, 2);
    /// assert!(!slice.is_empty());
    /// ```
    #[inline]
    pub fn is_empty(self) -> bool {
        self.metadata.is_zero()
    }
}

/// An iterator over a `Ref<[T]>` which produces `Ref<T>` values.
///
/// See [Ref::<[T]>::iter].
pub struct Iter<T, E, O> {
    start: usize,
    end: usize,
    _marker: PhantomData<(T, E, O)>,
}

impl<T: ZeroCopy, E: ByteOrder, O: Size> Iterator for Iter<T, E, O> {
    type Item = Ref<T, E, O>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.start == self.end {
            return None;
        }

        let start = self.start;
        self.start += size_of::<T>();
        Some(Ref::new(start))
    }
}

impl<T: ZeroCopy, E: ByteOrder, O: Size> DoubleEndedIterator for Iter<T, E, O> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.start == self.end {
            return None;
        }

        self.end -= size_of::<T>();
        Some(Ref::new(self.end))
    }
}

impl<T: ?Sized, E: ByteOrder, O: Size> Ref<T, E, O>
where
    T: Pointee,
{
    /// The number of elements in the slice.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::pointer::Ref;
    ///
    /// let slice = Ref::<str>::with_metadata(0, 10);
    /// assert_eq!(slice.metadata(), 10);
    /// ```
    #[inline]
    pub fn metadata(self) -> <T::Metadata as Packable>::Packed<O> {
        self.metadata
    }
}

impl<T, E: ByteOrder, O: Size> Ref<T, E, O>
where
    T: Pointee<Metadata = ()>,
{
    /// Construct a reference at the given offset.
    ///
    /// # Panics
    ///
    /// This will panic if either:
    /// * The `offset` can't be byte swapped as per
    ///   [`ZeroCopy::CAN_SWAP_BYTES`].
    /// * Packed [`offset()`] cannot be constructed from `U` (out of range).
    ///
    /// [`offset()`]: Self::offset
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::Ref;
    ///
    /// let reference = Ref::<u64>::new(42);
    /// assert_eq!(reference.offset(), 42);
    /// ```
    #[inline]
    pub fn new<U>(offset: U) -> Self
    where
        U: Copy + fmt::Debug,
        O: TryFrom<U>,
    {
        assert!(
            O::CAN_SWAP_BYTES,
            "Type `{}` cannot be byte-ordered since it would not inhabit valid types",
            any::type_name::<O>()
        );

        let Some(offset) = O::try_from(offset).ok() else {
            panic!("Offset {offset:?} not in the legal range 0-{}", O::MAX);
        };

        Self {
            offset: O::swap_bytes::<E>(offset),
            metadata: (),
            _marker: PhantomData,
        }
    }

    /// Construct a typed reference to the zeroeth offset in a buffer.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::Ref;
    ///
    /// let reference = Ref::<u64>::zero();
    /// assert_eq!(reference.offset(), 0);
    /// ```
    #[inline]
    pub const fn zero() -> Self {
        Self {
            offset: O::ZERO,
            metadata: (),
            _marker: PhantomData,
        }
    }
}

impl<T: ?Sized, E: ByteOrder, O: Size> Ref<T, E, O>
where
    T: Pointee,
{
    /// Get the offset the reference points to.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::Ref;
    ///
    /// let reference = Ref::<u64>::new(42);
    /// assert_eq!(reference.offset(), 42);
    /// ```
    #[inline]
    pub fn offset(self) -> usize {
        self.offset.as_usize::<E>()
    }

    /// Coerce from one kind of reference to another ensuring that the
    /// destination type `U` is size-compatible.
    ///
    /// This performs metadata conversion if the destination metadata for `U`
    /// differs from `T`, such as for `[u32]` to `[u8]` it would multiply the
    /// length by 4 to ensure that the slice points to an appropriately sized
    /// region.
    ///
    /// If the metadata conversion would overflow, this will wrap around the
    /// numerical bounds or panic for debug builds.
    ///
    /// See [`try_coerce()`] for more documentation, which is also a checked
    /// variant of this method.
    ///
    /// [`try_coerce()`]: Self::try_coerce
    pub fn coerce<U: ?Sized>(self) -> Ref<U, E, O>
    where
        T: Coerce<U>,
        U: Pointee,
    {
        Ref {
            offset: self.offset,
            metadata: T::coerce_metadata(self.metadata),
            _marker: PhantomData,
        }
    }

    /// Try to coerce from one kind of reference to another ensuring that the
    /// destination type `U` is size-compatible.
    ///
    /// This performs metadata conversion if the destination metadata for `U`
    /// differs from `T`, such as for `[u32]` to `[u8]` it would multiply the
    /// length by 4 to ensure that the slice points to an appropriately sized
    /// region.
    ///
    /// This returns `None` in case metadata would overflow due to the
    /// conversion.
    ///
    /// ```
    /// use musli_zerocopy::Ref;
    ///
    /// let reference: Ref<u64> = Ref::zero();
    /// let reference2 = reference.coerce::<[u32]>();
    /// assert_eq!(reference2.len(), 2);
    /// ```
    ///
    /// This method ensures that coercions across inappropriate types are
    /// prohibited, such as coercing from a reference to a slice which is too
    /// large.
    ///
    /// ```compile_fail
    /// use musli_zerocopy::Ref;
    ///
    /// let reference: Ref<u32> = Ref::zero();
    /// let reference2 = reference.coerce::<[u64]>();
    /// ```
    ///
    /// If metadata needs to be adjusted for the destination type such as for
    /// slices, it will be:
    ///
    /// ```
    /// use musli_zerocopy::Ref;
    ///
    /// let reference: Ref<[u32]> = Ref::with_metadata(0, 1);
    /// let reference2 = reference.try_coerce::<[u8]>().ok_or("bad coercion")?;
    /// assert_eq!(reference2.len(), 4);
    ///
    /// let reference: Ref<str> = Ref::with_metadata(0, 12);
    /// let reference2 = reference.try_coerce::<[u8]>().ok_or("bad coercion")?;
    /// assert_eq!(reference2.len(), 12);
    /// # Ok::<_, &'static str>(())
    /// ```
    ///
    /// This does mean that numerical overflow might occur if the packed
    /// metadata is too small:
    ///
    /// ```
    /// use musli_zerocopy::Ref;
    /// use musli_zerocopy::endian::Native;
    ///
    /// let reference = Ref::<[u32], Native, u8>::with_metadata(0, 64);
    /// let reference2 = reference.try_coerce::<[u8]>();
    /// assert!(reference2.is_none()); // 64 * 4 would overflow u8 packed metadata.
    /// ```
    ///
    /// Coercion of non-zero types are supported, but do not guarantee that the
    /// destination data is valid.
    pub fn try_coerce<U: ?Sized>(self) -> Option<Ref<U, E, O>>
    where
        T: Coerce<U>,
        U: Pointee,
    {
        Some(Ref {
            offset: self.offset,
            metadata: T::try_coerce_metadata(self.metadata)?,
            _marker: PhantomData,
        })
    }

    #[cfg(test)]
    pub(crate) fn cast<U: ?Sized>(self) -> Ref<U, E, O>
    where
        U: Pointee<Metadata = T::Metadata>,
    {
        Ref {
            offset: self.offset,
            metadata: self.metadata,
            _marker: PhantomData,
        }
    }
}

impl<T, const N: usize, E: ByteOrder, O: Size> Ref<[T; N], E, O>
where
    T: ZeroCopy,
{
    /// Coerce a reference to an array into a slice.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::OwnedBuf;
    ///
    /// let mut buf = OwnedBuf::new();
    ///
    /// let values = buf.store(&[1, 2, 3, 4]);
    /// let slice = values.array_into_slice();
    ///
    /// assert_eq!(buf.load(slice)?, &[1, 2, 3, 4]);
    /// # Ok::<_, musli_zerocopy::Error>(())
    /// ```
    #[inline]
    pub fn array_into_slice(self) -> Ref<[T], E, O> {
        Ref::with_metadata(self.offset, N)
    }
}

impl<T, E: ByteOrder, O: Size> Ref<MaybeUninit<T>, E, O>
where
    T: Pointee,
{
    /// Assume that the reference is initialized.
    ///
    /// Unlike the counterpart in Rust, this isn't actually unsafe. Because in
    /// order to load the reference again we'd have to validate it anyways.
    #[inline]
    pub const fn assume_init(self) -> Ref<T, E, O> {
        Ref {
            offset: self.offset,
            metadata: self.metadata,
            _marker: PhantomData,
        }
    }
}

impl<T: ?Sized, E: ByteOrder, O: Size> fmt::Debug for Ref<T, E, O>
where
    T: Pointee,
    <T::Metadata as Packable>::Packed<O>: fmt::Debug,
    O: fmt::Debug,
{
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Ref<{}> {{ offset: {:?}, metadata: {:?} }}",
            core::any::type_name::<T>(),
            self.offset,
            self.metadata,
        )
    }
}

impl<T: ?Sized, E: ByteOrder, O: Size> Clone for Ref<T, E, O>
where
    T: Pointee,
{
    #[inline]
    fn clone(&self) -> Self {
        *self
    }
}

impl<T: ?Sized, E: ByteOrder, O: Size> Copy for Ref<T, E, O> where T: Pointee {}

impl<T: ?Sized, E: ByteOrder, O: Size> PartialEq for Ref<T, E, O>
where
    T: Pointee,
    O: PartialEq,
    <T::Metadata as Packable>::Packed<O>: PartialEq,
{
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.offset == other.offset && self.metadata == other.metadata
    }
}

impl<T: ?Sized, E: ByteOrder, O: Size> Eq for Ref<T, E, O>
where
    T: Pointee,
    O: Eq,
    <T::Metadata as Packable>::Packed<O>: Eq,
{
}

impl<T: ?Sized, E: ByteOrder, O: Size> PartialOrd for Ref<T, E, O>
where
    T: Pointee,
    O: Ord,
    <T::Metadata as Packable>::Packed<O>: PartialOrd,
{
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match self.offset.partial_cmp(&other.offset) {
            Some(Ordering::Equal) => {}
            ord => return ord,
        }

        self.metadata.partial_cmp(&other.metadata)
    }
}

impl<T: ?Sized, E: ByteOrder, O: Size> Ord for Ref<T, E, O>
where
    T: Pointee,
    O: Ord,
    <T::Metadata as Packable>::Packed<O>: Ord,
{
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        match self.offset.cmp(&other.offset) {
            Ordering::Equal => {}
            ord => return ord,
        }

        self.metadata.cmp(&other.metadata)
    }
}

impl<T: ?Sized, E: ByteOrder, O: Size> Hash for Ref<T, E, O>
where
    T: Pointee,
    O: Hash,
    <T::Metadata as Packable>::Packed<O>: Hash,
{
    #[inline]
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.offset.hash(state);
        self.metadata.hash(state);
    }
}