offline 1.1.0

Ways to make things more or less aligned.
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
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
//! Things that only require [`core`].
//!
//! [`core`]: ::core
use core::{alloc::Layout, fmt, marker::PhantomData, mem, num::NonZero, ops, ptr};

/// Alias for [`Align::new`].
///
/// # Examples
///
/// ```
/// let aligner = offline::align::<16>();
/// ```
pub const fn align<const N: usize>() -> Align<N>
where
    Align<N>: Alignment,
{
    Align::new()
}

/// Alias for [`Padding::new`].
///
/// # Examples
///
/// ```
/// let padding = offline::padding::<16>();
/// ```
pub const fn padding<const N: usize>() -> Padding<N>
where
    Align<N>: Alignment,
{
    Padding::new()
}

/// Alias for [`Aligned::new`].
///
/// # Examples
///
/// ```
/// let aligned = offline::aligned::<[u8; 3], 16>([1, 2, 3]);
/// ```
pub const fn aligned<T, const N: usize>(value: T) -> Aligned<T, N>
where
    Align<N>: Alignment,
{
    Aligned::new(value)
}

/// Alias for [`Misaligned::new`].
///
/// # Examples
///
/// ```
/// let misaligned = offline::misaligned::<[u8; 3], 16>([1, 2, 3]);
/// ```
pub const fn misaligned<T: Unpadded, const N: usize>(value: T) -> Misaligned<T, N>
where
    Align<N>: Alignment,
{
    Misaligned::new(value)
}

/// Implementation of [`DynAlign`]. (16-bit pointers)
#[cfg(target_pointer_width = "16")]
#[repr(usize)]
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
enum InnerAlignment {
    #[default]
    _A0 = 0x1,
    _A1 = 0x2,
    _A2 = 0x4,
    _A3 = 0x8,
    _A4 = 0x10,
    _A5 = 0x20,
    _A6 = 0x40,
    _A7 = 0x80,
    _A8 = 0x100,
    _A9 = 0x200,
    _A10 = 0x400,
    _A11 = 0x800,
    _A12 = 0x1000,
    _A13 = 0x2000,
    _A14 = 0x4000,
    _A15 = 0x8000,
}

/// Implementation of [`DynAlign`]. (32/64-bit pointers)
#[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
#[repr(usize)]
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
enum InnerAlignment {
    #[default]
    _A0 = 0x1,
    _A1 = 0x2,
    _A2 = 0x4,
    _A3 = 0x8,
    _A4 = 0x10,
    _A5 = 0x20,
    _A6 = 0x40,
    _A7 = 0x80,
    _A8 = 0x100,
    _A9 = 0x200,
    _A10 = 0x400,
    _A11 = 0x800,
    _A12 = 0x1000,
    _A13 = 0x2000,
    _A14 = 0x4000,
    _A15 = 0x8000,
    _A16 = 0x10000,
    _A17 = 0x20000,
    _A18 = 0x40000,
    _A19 = 0x80000,
    _A20 = 0x100000,
    _A21 = 0x200000,
    _A22 = 0x400000,
    _A23 = 0x800000,
    _A24 = 0x1000000,
    _A25 = 0x2000000,
    _A26 = 0x4000000,
    _A27 = 0x8000000,
    _A28 = 0x10000000,
    _A29 = 0x20000000,
}
impl InnerAlignment {
    /// Maximum value (usize).
    #[cfg(target_pointer_width = "16")]
    const MAX: usize = 0x8000;

    /// Maximum value (usize).
    #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
    const MAX: usize = 0x20000000;
}

/// Alignment value.
///
/// Unlike [`core::ptr::Alignment`], this is limited to 2<sup>29</sup>,
/// like [`Align`].
#[repr(transparent)]
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct DynAlign(InnerAlignment);
impl DynAlign {
    /// Gets the alignment of a type.
    #[inline]
    pub const fn of<T>() -> DynAlign {
        // SAFETY: Types' alignment always are valid here.
        unsafe { DynAlign::from_usize_unchecked(mem::align_of::<T>()) }
    }

    /// Gets the alignment of a value.
    #[inline]
    pub const fn of_val<T: ?Sized>(val: &T) -> DynAlign {
        // SAFETY: Types' alignment always are valid here.
        unsafe { DynAlign::from_usize_unchecked(mem::align_of_val::<T>(val)) }
    }

    /// Creates a new alignment value from a `usize`.
    ///
    /// Returns `None` if the alignment is not a power of two or larger than
    /// 2<sup>29</sup>.
    #[inline]
    pub const fn from_usize(value: usize) -> Option<DynAlign> {
        if value.is_power_of_two() && value <= InnerAlignment::MAX {
            // SAFETY: The value is valid and repr(usize).
            Some(unsafe { DynAlign::from_usize_unchecked(value) })
        } else {
            None
        }
    }

    /// Creates an alignment value from a `usize` without checking for validity.
    ///
    /// # Safety
    ///
    /// The alignment must be a power of two and not larger than 2<sup>29</sup>.
    #[inline]
    pub const unsafe fn from_usize_unchecked(value: usize) -> DynAlign {
        // SAFETY: Guaranteed by caller.
        DynAlign(unsafe { mem::transmute::<usize, InnerAlignment>(value) })
    }

    /// Converts the alignment to a `usize`.
    #[inline]
    pub const fn to_usize(self) -> usize {
        self.0 as usize
    }

    /// Converts the alignment to a `NonZero<usize>`.
    #[inline]
    pub const fn to_nonzero_usize(self) -> NonZero<usize> {
        // SAFETY: Alignment is never zero.
        unsafe { NonZero::new_unchecked(self.to_usize()) }
    }

    /// Gets the layout of [`Padding`] for this alignment.
    #[inline]
    pub const fn padding_layout(self) -> Layout {
        // SAFETY: Alignment is always valid for padding.
        unsafe { Layout::from_size_align_unchecked(self.to_usize(), self.to_usize()) }
    }

    /// Gets the layout of [`Align`] for this alignment.
    #[inline]
    pub const fn align_layout(self) -> Layout {
        // SAFETY: Alignment is always valid for padding.
        unsafe { Layout::from_size_align_unchecked(0, self.to_usize()) }
    }
}
impl fmt::Debug for DynAlign {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let n = self.to_usize();
        let mut buf = *b"1 << 63";
        let len = if n < (1 << 10) {
            buf[5] = b'0' + (n.trailing_zeros() as u8);
            6
        } else {
            let exp = n.trailing_zeros() as u8;
            buf[5] = b'0' + (exp / 10);
            buf[6] = b'0' + (exp % 10);
            7
        };

        // SAFETY: We only output valid UTF-8.
        let s = unsafe { str::from_utf8_unchecked(&buf[..len]) };
        f.pad(s)
    }
}

/// Struct aligned to a particular number of bytes.
///
/// Because `repr(Rust)` allows rearranging fields, you should use [`Aligned`]
/// instead if you want to actually ensure that a particular value is aligned.
/// Otherwise, a field of this type simple ensures that its containing struct
/// is aligned, potentially leaving some fields unaligned.
#[derive(Copy, Clone)]
pub struct Align<const N: usize>([<Self as Alignment>::Align; 0])
where
    Align<N>: Alignment;
impl<const N: usize> Align<N>
where
    Align<N>: Alignment,
{
    /// Makes an alignment.
    #[inline]
    pub const fn new() -> Align<N> {
        Align([])
    }
}
impl<const N: usize> fmt::Debug for Align<N>
where
    Align<N>: Alignment,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (buf, len) = const {
            let mut buf = *b"Align<{1 << 63}>";
            let len = if N < (1 << 10) {
                buf[12] = b'0' + (N.trailing_zeros() as u8);
                buf[13] = b'}';
                buf[14] = b'>';
                15
            } else {
                let exp = N.trailing_zeros() as u8;
                buf[12] = b'0' + (exp / 10);
                buf[13] = b'0' + (exp % 10);
                16
            };
            (buf, len)
        };

        // SAFETY: We only output valid UTF-8.
        let s = unsafe { str::from_utf8_unchecked(&buf[..len]) };
        f.pad(s)
    }
}

/// Uninitialized bytes with a particular alignment.
///
/// Unlike regular padding, all bytes of this padding are guaranteed to be
/// preserved across copies.
#[derive(Copy, Clone)]
pub struct Padding<const N: usize>(mem::MaybeUninit<<Align<N> as Alignment>::Padding>)
where
    Align<N>: Alignment;
impl<const N: usize> Padding<N>
where
    Align<N>: Alignment,
{
    /// Makes padding.
    #[inline]
    pub const fn new() -> Padding<N> {
        Padding(mem::MaybeUninit::uninit())
    }
}
impl<const N: usize> fmt::Debug for Padding<N>
where
    Align<N>: Alignment,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (buf, len) = const {
            let mut buf = *b"Padding<{1 << 63}>";
            let len = if N < (1 << 10) {
                buf[14] = b'0' + (N.trailing_zeros() as u8);
                buf[15] = b'}';
                buf[16] = b'>';
                17
            } else {
                let exp = N.trailing_zeros() as u8;
                buf[14] = b'0' + (exp / 10);
                buf[15] = b'0' + (exp % 10);
                18
            };
            (buf, len)
        };

        // SAFETY: We only output valid UTF-8.
        let s = unsafe { str::from_utf8_unchecked(&buf[..len]) };
        f.pad(s)
    }
}

/// Sealed module.
mod sealed {
    /// Sealed trait.
    pub trait Sealed {}
}

/// Valid [`Align`]ment.
///
/// Due to restrictions in the compiler, this only allows alignments up to
/// 2<sup>29</sup>. The alignments between 2<sup>16</sup> are conditional on
/// the target pointer width being 32 bits or higher.
pub trait Alignment: sealed::Sealed {
    /// Dynamic version of alignment.
    #[doc(hidden)]
    const DYN: DynAlign;

    /// Type which satisfies the alignment.
    #[doc(hidden)]
    type Align: 'static + Copy;

    /// Padding for the alignment of a particular type.
    #[doc(hidden)]
    type Padding: 'static + Copy;
}

/// Creates "aligner" structs which have a specified alignment.
macro_rules! align {
    (
        $($vis:vis struct $A:ident = $align:literal;)*
    ) => {
        $(
            #[repr(align($align))]
            #[allow(missing_debug_implementations)]
            #[derive(Copy, Clone)]
            $vis struct $A;

            impl sealed::Sealed for Align<$align> {}
            impl Alignment for Align<$align> {
                const DYN: DynAlign = DynAlign::from_usize($align).unwrap();
                type Align = $A;
                type Padding = [u8; $align];
            }
        )*
    }
}

align! {
    pub struct A0 = 0x1;
    pub struct A1 = 0x2;
    pub struct A2 = 0x4;
    pub struct A3 = 0x8;
    pub struct A4 = 0x10;
    pub struct A5 = 0x20;
    pub struct A6 = 0x40;
    pub struct A7 = 0x80;
    pub struct A8 = 0x100;
    pub struct A9 = 0x200;
    pub struct A10 = 0x400;
    pub struct A11 = 0x800;
    pub struct A12 = 0x1000;
    pub struct A13 = 0x2000;
    pub struct A14 = 0x4000;
    pub struct A15 = 0x8000;
}
#[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
align! {
    pub struct A16 = 0x10000;
    pub struct A17 = 0x20000;
    pub struct A18 = 0x40000;
    pub struct A19 = 0x80000;
    pub struct A20 = 0x100000;
    pub struct A21 = 0x200000;
    pub struct A22 = 0x400000;
    pub struct A23 = 0x800000;
    pub struct A24 = 0x1000000;
    pub struct A25 = 0x2000000;
    pub struct A26 = 0x4000000;
    pub struct A27 = 0x8000000;
    pub struct A28 = 0x10000000;
    pub struct A29 = 0x20000000;
    /*
    pub struct A30 = 0x40000000;
    pub struct A31 = 0x80000000;
    */
}
/*
#[cfg(target_pointer_width = "64")]
aligner! {
    pub struct A32 = 0x100000000;
    pub struct A33 = 0x200000000;
    pub struct A34 = 0x400000000;
    pub struct A35 = 0x800000000;
    pub struct A36 = 0x1000000000;
    pub struct A37 = 0x2000000000;
    pub struct A38 = 0x4000000000;
    pub struct A39 = 0x8000000000;
    pub struct A40 = 0x10000000000;
    pub struct A41 = 0x20000000000;
    pub struct A42 = 0x40000000000;
    pub struct A43 = 0x80000000000;
    pub struct A44 = 0x100000000000;
    pub struct A45 = 0x200000000000;
    pub struct A46 = 0x400000000000;
    pub struct A47 = 0x800000000000;
    pub struct A48 = 0x1000000000000;
    pub struct A49 = 0x2000000000000;
    pub struct A50 = 0x4000000000000;
    pub struct A51 = 0x8000000000000;
    pub struct A52 = 0x10000000000000;
    pub struct A53 = 0x20000000000000;
    pub struct A54 = 0x40000000000000;
    pub struct A55 = 0x80000000000000;
    pub struct A56 = 0x100000000000000;
    pub struct A57 = 0x200000000000000;
    pub struct A58 = 0x400000000000000;
    pub struct A59 = 0x800000000000000;
    pub struct A60 = 0x1000000000000000;
    pub struct A61 = 0x2000000000000000;
    pub struct A62 = 0x4000000000000000;
    pub struct A63 = 0x8000000000000000;
}
*/

/// Aligns a type to a given number of bytes.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Aligned<T, const N: usize>
where
    Align<N>: Alignment,
{
    /// Aligner.
    align: Align<N>,

    /// Aligned value.
    inner: T,
}
impl<T, const N: usize> Aligned<T, N>
where
    Align<N>: Alignment,
{
    /// Create new aligned value.
    pub const fn new(inner: T) -> Aligned<T, N> {
        Aligned {
            align: Align([]),
            inner,
        }
    }

    /// Return unaligned value.
    pub const fn into_inner(self) -> T {
        // SAFETY: We immediately forget `self` to avoid double-drop.
        let inner = unsafe { mem::transmute_copy(&self) };
        mem::forget(self);
        inner
    }
}
impl<T, const N: usize> ops::Deref for Aligned<T, N>
where
    Align<N>: Alignment,
{
    type Target = T;

    #[inline]
    fn deref(&self) -> &T {
        &self.inner
    }
}
impl<T, const N: usize> ops::DerefMut for Aligned<T, N>
where
    Align<N>: Alignment,
{
    #[inline]
    fn deref_mut(&mut self) -> &mut T {
        &mut self.inner
    }
}

/// Opt-in guarantee that a type does not contain any padding bytes.
///
/// Note that this does not mean that all values of a type have to be
/// possible, just that when the type is copied, all of its bytes are copied.
///
/// This is required, for the moment, to ensure that [`Misaligned`] works
/// correctly. Ideally, it will not be required in the future.
#[cfg_attr(feature = "nightly", marker)]
pub trait Unpadded {}
impl<T: Unpadded, const N: usize> Unpadded for [T; N] {}
impl<T> Unpadded for PhantomData<T> {}
impl<const N: usize> Unpadded for Align<N> where Align<N>: Alignment {}
impl<const N: usize> Unpadded for Padding<N> where Align<N>: Alignment {}

#[cfg(feature = "nightly")]
impl<T> Unpadded for [T; 0] {}

/// Implements [`Unpadded`] for a type.
macro_rules! impl_unpadded {
    ($($t:ty),* $(,)?) => {
        $(
            impl Unpadded for $t {}
        )*
    }
}
impl_unpadded! {
    bool,
    u8,
    u16,
    u32,
    u64,
    u128,
    usize,
    i8,
    i16,
    i32,
    i64,
    i128,
    isize,
    char,
    NonZero<u8>,
    NonZero<u16>,
    NonZero<u32>,
    NonZero<u64>,
    NonZero<u128>,
    NonZero<usize>,
    NonZero<i8>,
    NonZero<i16>,
    NonZero<i32>,
    NonZero<i64>,
    NonZero<i128>,
    NonZero<isize>,
    NonZero<char>,
    (),
}

/// Padding for [`Misaligned`].
///
/// This has to be a union to ensure that, if `T` is more aligned than `N`,
/// we still have non-padding bytes to write `T` in.
#[repr(C)]
union MisalignedPadding<T, const N: usize>
where
    Align<N>: Alignment,
{
    /// Padding.
    padding: Padding<N>,

    /// Value.
    value: mem::ManuallyDrop<T>,
}

/// Ensures that a type is *not* aligned to a given number of bytes.
///
/// `T` will have its own alignment, but all higher alignments up to `N` will
/// not be satisfied. This involves padding of at least `N` bytes, but probably
/// more.
#[repr(C)]
pub struct Misaligned<T: Unpadded, const N: usize>
where
    Align<N>: Alignment,
{
    /// Aligner.
    align: Align<N>,

    /// Padding.
    padding: mem::MaybeUninit<MisalignedPadding<T, N>>,

    /// Value.
    value: mem::MaybeUninit<T>,
}
impl<T: Unpadded, const N: usize> Misaligned<T, N>
where
    Align<N>: Alignment,
{
    /// Write offset of value.
    pub(crate) const OFFSET: usize = mem::offset_of!(Misaligned<T, N>, value) - align_of::<T>();

    /// Create new aligned value.
    pub const fn new(inner: T) -> Misaligned<T, N> {
        let mut base: Self = Misaligned {
            align: Align([]),
            padding: mem::MaybeUninit::uninit(),
            value: mem::MaybeUninit::uninit(),
        };
        base.as_mut_uninit().write(inner);
        base
    }

    /// Get maybe-uninit value inside.
    const fn as_uninit(&self) -> &mem::MaybeUninit<T> {
        // SAFETY: All bytes inside this range are maybe-uninit,
        // and the.
        unsafe {
            &*ptr::from_ref(self)
                .byte_add(Self::OFFSET)
                .cast::<T>()
                .cast::<mem::MaybeUninit<T>>()
        }
    }

    /// Get maybe-uninit value inside.
    const fn as_mut_uninit(&mut self) -> &mut mem::MaybeUninit<T> {
        // SAFETY: All bytes inside this range are maybe-uninit.
        unsafe {
            &mut *ptr::from_mut(self)
                .byte_add(Self::OFFSET)
                .cast::<T>()
                .cast::<mem::MaybeUninit<T>>()
        }
    }

    /// Return unaligned value.
    pub const fn into_inner(self) -> T {
        // SAFETY: We immediately forget `self` to avoid double-drop.
        let inner = unsafe { self.as_uninit().assume_init_read() };
        mem::forget(self);
        inner
    }
}
impl<T: Unpadded, const N: usize> ops::Deref for Misaligned<T, N>
where
    Align<N>: Alignment,
{
    type Target = T;

    #[inline]
    fn deref(&self) -> &T {
        // SAFETY: We always initialize T.
        unsafe { self.as_uninit().assume_init_ref() }
    }
}
impl<T: Unpadded, const N: usize> ops::DerefMut for Misaligned<T, N>
where
    Align<N>: Alignment,
{
    #[inline]
    fn deref_mut(&mut self) -> &mut T {
        // SAFETY: We always initialize T.
        unsafe { self.as_mut_uninit().assume_init_mut() }
    }
}
impl<T: Unpadded, const N: usize> Drop for Misaligned<T, N>
where
    Align<N>: Alignment,
{
    #[inline]
    fn drop(&mut self) {
        // SAFETY: We always initialize T.
        unsafe { self.as_mut_uninit().assume_init_drop() }
    }
}

/// Trivial implementations for traits.
#[cfg_attr(any(feature = "nightly", coverage_nightly), coverage(off))]
#[cfg_attr(test, mutants::skip)]
mod trivial_impls {
    use core::{cmp, fmt, hash, mem};

    use crate::core::{Align, Aligned, Alignment, Misaligned, Padding, Unpadded};

    impl<const N: usize> PartialEq for Align<N>
    where
        Align<N>: Alignment,
    {
        #[inline]
        fn eq(&self, _: &Self) -> bool {
            true
        }
    }
    impl<const N: usize> Eq for Align<N> where Align<N>: Alignment {}
    #[expect(clippy::non_canonical_partial_ord_impl)]
    impl<const N: usize> PartialOrd for Align<N>
    where
        Align<N>: Alignment,
    {
        #[inline]
        fn partial_cmp(&self, _: &Align<N>) -> Option<cmp::Ordering> {
            Some(cmp::Ordering::Equal)
        }
    }
    impl<const N: usize> Ord for Align<N>
    where
        Align<N>: Alignment,
    {
        #[inline]
        fn cmp(&self, _: &Align<N>) -> cmp::Ordering {
            cmp::Ordering::Equal
        }
    }
    impl<const N: usize> hash::Hash for Align<N>
    where
        Align<N>: Alignment,
    {
        #[inline]
        fn hash<H: hash::Hasher>(&self, _: &mut H) {}
    }
    impl<const N: usize> Default for Align<N>
    where
        Align<N>: Alignment,
    {
        #[inline]
        fn default() -> Align<N> {
            Align([])
        }
    }

    impl<const N: usize> PartialEq for Padding<N>
    where
        Align<N>: Alignment,
    {
        #[inline]
        fn eq(&self, _: &Self) -> bool {
            true
        }
    }
    impl<const N: usize> Eq for Padding<N> where Align<N>: Alignment {}
    #[expect(clippy::non_canonical_partial_ord_impl)]
    impl<const N: usize> PartialOrd for Padding<N>
    where
        Align<N>: Alignment,
    {
        #[inline]
        fn partial_cmp(&self, _: &Padding<N>) -> Option<cmp::Ordering> {
            Some(cmp::Ordering::Equal)
        }
    }
    impl<const N: usize> Ord for Padding<N>
    where
        Align<N>: Alignment,
    {
        #[inline]
        fn cmp(&self, _: &Padding<N>) -> cmp::Ordering {
            cmp::Ordering::Equal
        }
    }
    impl<const N: usize> hash::Hash for Padding<N>
    where
        Align<N>: Alignment,
    {
        #[inline]
        fn hash<H: hash::Hasher>(&self, _: &mut H) {}
    }
    impl<const N: usize> Default for Padding<N>
    where
        Align<N>: Alignment,
    {
        #[inline]
        fn default() -> Padding<N> {
            Padding(mem::MaybeUninit::uninit())
        }
    }

    impl<T: Unpadded + Clone, const N: usize> Clone for Misaligned<T, N>
    where
        Align<N>: Alignment,
    {
        #[inline]
        fn clone(&self) -> Misaligned<T, N> {
            Misaligned::new((**self).clone())
        }
    }
    // can't conditionally implement destructor, so, can't be Copy
    // impl<T: Copy, const N: usize> Copy for Misaligned<T, N> where Align<N>: Alignment {}
    impl<T: Unpadded + PartialEq, const N: usize> PartialEq for Misaligned<T, N>
    where
        Align<N>: Alignment,
    {
        #[inline]
        fn eq(&self, other: &Misaligned<T, N>) -> bool {
            **self == **other
        }
    }
    impl<T: Unpadded + Eq, const N: usize> Eq for Misaligned<T, N> where Align<N>: Alignment {}
    impl<T: Unpadded + PartialOrd, const N: usize> PartialOrd for Misaligned<T, N>
    where
        Align<N>: Alignment,
    {
        #[inline]
        fn partial_cmp(&self, other: &Misaligned<T, N>) -> Option<cmp::Ordering> {
            PartialOrd::partial_cmp(&**self, &**other)
        }
    }
    impl<T: Unpadded + Ord, const N: usize> Ord for Misaligned<T, N>
    where
        Align<N>: Alignment,
    {
        #[inline]
        fn cmp(&self, other: &Misaligned<T, N>) -> cmp::Ordering {
            Ord::cmp(&**self, &**other)
        }
    }
    impl<T: Unpadded + hash::Hash, const N: usize> hash::Hash for Misaligned<T, N>
    where
        Align<N>: Alignment,
    {
        #[inline]
        fn hash<H: hash::Hasher>(&self, state: &mut H) {
            hash::Hash::hash(&**self, state);
        }
    }
    impl<T: Unpadded + Default, const N: usize> Default for Misaligned<T, N>
    where
        Align<N>: Alignment,
    {
        #[inline]
        fn default() -> Misaligned<T, N> {
            Misaligned::new(Default::default())
        }
    }

    /// Implements formatting traits for [`Aligned`].
    macro_rules! fmt_impl_aligned {
        (
            $($trait:ident),* $(,)?
        ) => {
            $(
                impl<T: fmt::$trait, const N: usize> fmt::$trait for Aligned<T, N>
                where
                    Align<N>: Alignment,
                {
                    #[inline]
                    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                        fmt::$trait::fmt(&**self, f)
                    }
                }
            )*
        }
    }
    /// Implements formatting traits for [`Misaligned`].
    macro_rules! fmt_impl_misaligned {
        ($($trait:ident),* $(,)?) => {
            $(
                impl<T: Unpadded + fmt::$trait, const N: usize> fmt::$trait for Misaligned<T, N>
                where
                    Align<N>: Alignment,
                {
                    #[inline]
                    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                        fmt::$trait::fmt(&**self, f)
                    }
                }
            )*
        }
    }
    fmt_impl_aligned! {
        Binary,
        Debug,
        Display,
        LowerExp,
        LowerHex,
        Octal,
        Pointer,
        UpperExp,
        UpperHex,
    }
    fmt_impl_misaligned! {
        Binary,
        Debug,
        Display,
        LowerExp,
        LowerHex,
        Octal,
        Pointer,
        UpperExp,
        UpperHex,
    }
}

#[cfg(test)]
mod tests {
    use core::{
        mem::align_of,
        sync::atomic::{AtomicUsize, Ordering},
    };

    use crate::core::{Align, Alignment, Padding, Unpadded, aligned, misaligned};

    macro_rules! check_aligned {
        ($t:ty, $align:literal) => {
            let mut val = aligned::<$t, $align>(0);
            *val = 1;
            assert_eq!(*val, 1);
            assert_eq!(val.into_inner(), 1);

            assert_eq!(
                (&raw const *aligned::<$t, $align>(0)).align_offset($align),
                0,
                concat!(stringify!($t), " was not ", stringify!($align), "-aligned"),
            );
        };
    }

    macro_rules! check_misaligned {
        ($value:literal: $t:ty, $align:literal) => {
            let val = misaligned::<$t, $align>($value);
            assert_eq!(
                *val, $value,
                concat!(
                    stringify!($t),
                    " when ",
                    stringify!($align),
                    "-misaligned has incorrect value"
                ),
            );
            assert_eq!(
                val.into_inner(),
                $value,
                concat!(
                    stringify!($t),
                    " when ",
                    stringify!($align),
                    "-misaligned has incorrect value"
                ),
            );
            let mut val = misaligned::<$t, $align>(0);
            *val = $value;
            assert_eq!(
                *val, $value,
                concat!(
                    stringify!($t),
                    " when ",
                    stringify!($align),
                    "-misaligned has incorrect value"
                ),
            );
            let mut power = align_of::<$t>();
            loop {
                power <<= 1;
                if power >= $align {
                    break;
                }
                assert_ne!(
                    (&raw const *val).align_offset(power),
                    0,
                    concat!(
                        stringify!($t),
                        " when ",
                        stringify!($align),
                        "-misaligned was {}-aligned"
                    ),
                    power,
                );
            }
        };
    }

    // required to avoid stack overflow
    fn box_padding<const N: usize>() -> Box<Padding<N>>
    where
        Align<N>: Alignment,
    {
        // SAFETY: This is already uninitialized, so, it's okay.
        unsafe { Box::new_uninit().assume_init() }
    }

    // required to avoid stack overflow
    fn box_align<const N: usize>() -> Box<Align<N>>
    where
        Align<N>: Alignment,
    {
        // SAFETY: This is a ZST, so, it's okay.
        unsafe { Box::new_uninit().assume_init() }
    }

    #[test]
    fn test_debug_padding() {
        assert_eq!(
            format!("{:?}", box_padding::<{ 1 << 0 }>()),
            "Padding<{1 << 0}>"
        );
        assert_eq!(
            format!("{:?}", box_padding::<{ 1 << 9 }>()),
            "Padding<{1 << 9}>"
        );
        assert_eq!(
            format!("{:?}", box_padding::<{ 1 << 10 }>()),
            "Padding<{1 << 10}>"
        );
        assert_eq!(
            format!("{:?}", box_padding::<{ 1 << 11 }>()),
            "Padding<{1 << 11}>"
        );
        assert_eq!(
            format!("{:?}", box_padding::<{ 1 << 21 }>()),
            "Padding<{1 << 21}>"
        );
    }

    #[test]
    fn test_debug_align() {
        assert_eq!(
            format!("{:?}", box_align::<{ 1 << 0 }>()),
            "Align<{1 << 0}>"
        );
        assert_eq!(
            format!("{:?}", box_align::<{ 1 << 9 }>()),
            "Align<{1 << 9}>"
        );
        assert_eq!(
            format!("{:?}", box_align::<{ 1 << 10 }>()),
            "Align<{1 << 10}>"
        );
        assert_eq!(
            format!("{:?}", box_align::<{ 1 << 11 }>()),
            "Align<{1 << 11}>"
        );
        assert_eq!(
            format!("{:?}", box_align::<{ 1 << 21 }>()),
            "Align<{1 << 21}>"
        );
    }

    #[test]
    fn test_underaligned() {
        check_aligned!(u8, 1);
        check_aligned!(u16, 1);
        check_aligned!(u16, 2);
        check_aligned!(u32, 1);
        check_aligned!(u32, 2);
        check_aligned!(u32, 4);
        check_aligned!(u64, 1);
        check_aligned!(u64, 2);
        check_aligned!(u64, 4);
        check_aligned!(u64, 8);
        check_aligned!(u128, 1);
        check_aligned!(u128, 2);
        check_aligned!(u128, 4);
        check_aligned!(u128, 8);
        check_aligned!(u128, 16);
    }

    #[test]
    fn test_overaligned() {
        check_aligned!(u8, 2);
        check_aligned!(u8, 4);
        check_aligned!(u8, 8);
        check_aligned!(u8, 16);
        check_aligned!(u8, 32);
        check_aligned!(u8, 64);
        check_aligned!(u8, 128);
        check_aligned!(u8, 256);
        check_aligned!(u8, 512);
        check_aligned!(u16, 4);
        check_aligned!(u16, 8);
        check_aligned!(u16, 16);
        check_aligned!(u16, 32);
        check_aligned!(u16, 64);
        check_aligned!(u16, 128);
        check_aligned!(u16, 256);
        check_aligned!(u16, 512);
        check_aligned!(u32, 8);
        check_aligned!(u32, 16);
        check_aligned!(u32, 32);
        check_aligned!(u32, 64);
        check_aligned!(u32, 128);
        check_aligned!(u32, 256);
        check_aligned!(u32, 512);
        check_aligned!(u64, 16);
        check_aligned!(u64, 32);
        check_aligned!(u64, 64);
        check_aligned!(u64, 128);
        check_aligned!(u64, 256);
        check_aligned!(u64, 512);
        check_aligned!(u128, 32);
        check_aligned!(u128, 64);
        check_aligned!(u128, 128);
        check_aligned!(u128, 256);
        check_aligned!(u128, 512);
    }

    #[test]
    fn test_padding_size() {
        assert_eq!(size_of::<Padding<1>>(), 1);
        assert_eq!(size_of::<Padding<2>>(), 2);
        assert_eq!(size_of::<Padding<4>>(), 4);
        assert_eq!(size_of::<Padding<8>>(), 8);
        assert_eq!(size_of::<Padding<16>>(), 16);
        assert_eq!(size_of::<Padding<32>>(), 32);
        assert_eq!(size_of::<Padding<64>>(), 64);
        assert_eq!(size_of::<Padding<128>>(), 128);
        assert_eq!(size_of::<Padding<256>>(), 256);
        assert_eq!(size_of::<Padding<512>>(), 512);
    }

    #[test]
    fn test_not_misaligned() {
        check_misaligned!(0x11: u8, 1);
        check_misaligned!(0x1122: u16, 1);
        check_misaligned!(0x1122: u16, 2);
        check_misaligned!(0x1122: u32, 1);
        check_misaligned!(0x11223344: u32, 2);
        check_misaligned!(0x11223344: u32, 4);
        check_misaligned!(0x1122334455667788: u64, 1);
        check_misaligned!(0x1122334455667788: u64, 2);
        check_misaligned!(0x1122334455667788: u64, 4);
        check_misaligned!(0x1122334455667788: u64, 8);
        check_misaligned!(0x11223344556677887766554433221100: u128, 1);
        check_misaligned!(0x11223344556677887766554433221100: u128, 2);
        check_misaligned!(0x11223344556677887766554433221100: u128, 4);
        check_misaligned!(0x11223344556677887766554433221100: u128, 8);
        check_misaligned!(0x11223344556677887766554433221100: u128, 16);
    }

    #[test]
    fn test_misaligned() {
        check_misaligned!(0x11: u8, 2);
        check_misaligned!(0x11: u8, 4);
        check_misaligned!(0x11: u8, 8);
        check_misaligned!(0x11: u8, 16);
        check_misaligned!(0x11: u8, 32);
        check_misaligned!(0x11: u8, 64);
        check_misaligned!(0x11: u8, 128);
        check_misaligned!(0x11: u8, 256);
        check_misaligned!(0x11: u8, 512);
        check_misaligned!(0x1122: u16, 4);
        check_misaligned!(0x1122: u16, 8);
        check_misaligned!(0x1122: u16, 16);
        check_misaligned!(0x1122: u16, 32);
        check_misaligned!(0x1122: u16, 64);
        check_misaligned!(0x1122: u16, 128);
        check_misaligned!(0x1122: u16, 256);
        check_misaligned!(0x1122: u16, 512);
        check_misaligned!(0x11223344: u32, 8);
        check_misaligned!(0x11223344: u32, 16);
        check_misaligned!(0x11223344: u32, 32);
        check_misaligned!(0x11223344: u32, 64);
        check_misaligned!(0x11223344: u32, 128);
        check_misaligned!(0x11223344: u32, 256);
        check_misaligned!(0x11223344: u32, 512);
        check_misaligned!(0x1122334455667788: u64, 16);
        check_misaligned!(0x1122334455667788: u64, 32);
        check_misaligned!(0x1122334455667788: u64, 64);
        check_misaligned!(0x1122334455667788: u64, 128);
        check_misaligned!(0x1122334455667788: u64, 256);
        check_misaligned!(0x1122334455667788: u64, 512);
        check_misaligned!(0x11223344556677887766554433221100: u128, 32);
        check_misaligned!(0x11223344556677887766554433221100: u128, 64);
        check_misaligned!(0x11223344556677887766554433221100: u128, 128);
        check_misaligned!(0x11223344556677887766554433221100: u128, 256);
        check_misaligned!(0x11223344556677887766554433221100: u128, 512);
    }

    // FIXME: padding byte hell
    // https://github.com/rust-lang/unsafe-code-guidelines/issues/599
    fn try_misaligned_drop<const N: usize>(counter: &AtomicUsize) {
        struct MyTest<'a>(usize, &'a AtomicUsize);
        impl Unpadded for MyTest<'_> {}
        impl Drop for MyTest<'_> {
            fn drop(&mut self) {
                if self.0 == 0x1122 {
                    self.1.fetch_add(1, Ordering::Relaxed);
                }
            }
        }
        let _ = misaligned::<MyTest, 1>(MyTest(0x1122, counter));

        // to test mismatched branch
        let _ = misaligned::<MyTest, 1>(MyTest(0, counter));
    }

    #[test]
    fn test_misaligned_drop() {
        let counter = AtomicUsize::new(0);
        try_misaligned_drop::<1>(&counter);
        try_misaligned_drop::<2>(&counter);
        try_misaligned_drop::<4>(&counter);
        try_misaligned_drop::<8>(&counter);
        try_misaligned_drop::<16>(&counter);
        assert_eq!(counter.load(Ordering::Relaxed), 5);
    }
}