erratic 0.13.2

Handling errors in an efficient way.
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
use alloc::boxed::Box;
use core::{
    error::{self, Error},
    fmt::{self, Debug, Display},
    marker::PhantomData,
    mem::{self, ManuallyDrop, MaybeUninit, swap},
    ptr::{self, NonNull},
    result,
};

/// Only the least significant 2 bits are used.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Metadata(pub u8);

impl Metadata {
    pub const MASK: u8 = 0b00000011;

    pub const _0: Metadata = Metadata(0b00000000);
    pub const _1: Metadata = Metadata(0b00000001);
    pub const _2: Metadata = Metadata(0b00000010);
    pub const _3: Metadata = Metadata(0b00000011);

    fn encode_in_byte(self, addr_bytes: &mut u8) {
        *addr_bytes |= self.0;
    }

    fn decode_from_byte(addr_bytes: &mut u8) -> Self {
        let meta = *addr_bytes & Self::MASK;
        *addr_bytes &= !Self::MASK;
        Self(meta)
    }
}

// An inline pointer-sized storage that having a metadata at the first byte.
// Note: The repr/align attribute is required as it is used to compute the offset
// that satisfies the alignment of T.
cfg_select! {
    target_pointer_width = "16" => {
        #[repr(C, align(2))]
        pub struct Align4PtrCompat<T> {
            meta: u8,
            store: MaybeUninit<[u8; 1]>,
            _marker: PhantomData<T>,
        }
    },
    target_pointer_width = "32" => {
        #[repr(C, align(4))]
        pub struct Align4PtrCompat<T> {
            meta: u8,
            store: MaybeUninit<[u8; 3]>,
            _marker: PhantomData<T>,
        }
    },
    target_pointer_width = "64" => {
        #[repr(C, align(8))]
        pub struct Align4PtrCompat<T> {
            meta: u8,
            store: MaybeUninit<[u8; 7]>,
            _marker: PhantomData<T>,
        }
    },
}

impl<T> Align4PtrCompat<T> {
    const fn offset_in_store() -> Option<isize> {
        const fn ty_of_field<T, F>(_: fn(T) -> F) -> usize {
            mem::size_of::<F>()
        }

        let target_size = mem::size_of::<T>();
        let target_align = mem::align_of::<T>();
        let store_offset_start = mem::offset_of!(Self, store);
        let store_size = ty_of_field(|v: Self| v.store);
        let store_offset_end = store_offset_start + store_size;

        let mut offset = store_offset_start;
        while offset <= store_offset_end {
            // Note: Rust guarantees that the alignment is not smaller than 1, even for ZSTs.
            // https://doc.rust-lang.org/reference/type-layout.html#size-and-alignment
            if offset.is_multiple_of(target_align) && store_offset_end - offset >= target_size {
                return Some((offset - store_offset_start) as isize);
            }

            offset += 1;
        }

        None
    }

    pub fn new(meta: Metadata, value: T) -> result::Result<Self, T> {
        let Some(offset) = Self::offset_in_store() else {
            return Err(value);
        };
        let mut this = unsafe {
            Self {
                meta: meta.0,
                store: mem::zeroed(),
                _marker: PhantomData,
            }
        };

        unsafe {
            // Safety: The offset is validated in `Self::offset_in_store`.
            ((&raw mut this.store).cast::<u8>().offset(offset) as *mut T).write(value);
        }

        Ok(this)
    }

    pub fn borrow_value(&self) -> &T {
        unsafe {
            let offset = Self::offset_in_store()
                .expect("offset_in_store was checked before creating an Align4PtrCompat");

            // Safety: The offset is validated prior to creating Align4PtrCompat.
            // The raw pointer, though invalidated by the newly created reference,
            // is not used afterward.
            &*((&raw const self.store).cast::<u8>().offset(offset) as *const T)
        }
    }

    pub fn into_value(self) -> T {
        unsafe {
            let offset = Self::offset_in_store()
                .expect("offset_in_store was checked before creating an Align4PtrCompat");

            let mut this = ManuallyDrop::new(self);
            let value_mut = (&raw mut this.store).cast::<u8>().offset(offset) as *mut T;

            value_mut.read()
        }
    }

    pub fn replace_value(&mut self, value: T) -> T {
        unsafe {
            let offset = Self::offset_in_store()
                .expect("offset_in_store was checked before creating an Align4PtrCompat");

            // Safety: The offset is validated prior to creating Align4PtrCompat.
            // The raw pointer, though invalidated by the newly created reference,
            // is not used afterward.
            ptr::replace(
                (&raw mut self.store).cast::<u8>().offset(offset) as *mut T,
                value,
            )
        }
    }
}

impl<T> Drop for Align4PtrCompat<T> {
    fn drop(&mut self) {
        let offset = Self::offset_in_store()
            .expect("offset_in_store was checked before creating an Align4PtrCompat");

        unsafe {
            // Safety: The offset is validated prior to creating Align4PtrCompat.
            ptr::drop_in_place((&raw mut self.store).cast::<u8>().offset(offset) as *mut T);
        }
    }
}

/// A non-null transformed address with metadata encoded in the low 2 bits of the first byte.
#[derive(Clone, Copy)]
struct Align4Ptr(NonNull<()>);

impl Align4Ptr {
    fn swap_leading_and_trailing_byte_on_big_endian(addr_bytes: &mut [u8]) {
        let index_last = addr_bytes.len() - 1;
        let (leading_bytes, last_byte) = addr_bytes.split_at_mut(index_last);
        cfg_select! {
            target_endian = "big" => swap(&mut leading_bytes[0], &mut last_byte[0]),
            target_endian = "little" => _ = || { swap(&mut leading_bytes[0], &mut last_byte[0]) }, // No-op for little endian
        }
    }

    /// Encodes `meta` into the low 2 bits of the pointer address.
    ///
    /// # Panics
    ///
    /// Panics if the low 2 bits of `addr` are not zero.
    fn from_parts(ptr: NonNull<()>, meta: Metadata) -> Self {
        let ptr = ptr.as_ptr();
        let addr = ptr.map_addr(|addr| {
            let mut addr_bytes = addr.to_le_bytes();

            assert_eq!(addr_bytes[0] & Metadata::MASK, 0);

            meta.encode_in_byte(&mut addr_bytes[0]);
            Self::swap_leading_and_trailing_byte_on_big_endian(&mut addr_bytes);

            usize::from_le_bytes(addr_bytes)
        });

        unsafe {
            // Safety: swapping bytes keeps the addr non-zero.
            Self(NonNull::new_unchecked(addr))
        }
    }

    /// Extracts the original address and metadata from the encoded pointer.
    fn into_parts(self) -> (NonNull<()>, Metadata) {
        let addr = self.0.as_ptr();

        let mut meta = Metadata::_0;
        let ptr = addr.map_addr(|addr| {
            let mut addr_bytes = addr.to_le_bytes();

            Self::swap_leading_and_trailing_byte_on_big_endian(&mut addr_bytes);
            meta = Metadata::decode_from_byte(&mut addr_bytes[0]);

            usize::from_le_bytes(addr_bytes)
        });

        unsafe {
            // Safety: `Align4Ptr` guarantees the pointer is non-null.
            (NonNull::new_unchecked(ptr), meta)
        }
    }
}

#[repr(C, align(4))]
pub struct Align4<T: ?Sized>(pub T);

impl<T> Debug for Align4<T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Debug::fmt(&self.0, f)
    }
}

impl<T> Display for Align4<T>
where
    T: Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Display::fmt(&self.0, f)
    }
}

impl<T> error::Error for Align4<T>
where
    T: Error,
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.0.source()
    }
}

/// Owned pointer with metadata stored in the low 2 bits of the first byte of the pointer.
///
/// # Safety invariants
///
/// - The stored address was originally obtained from [`Box::into_raw`],
///   so it must only be freed once via [`into_boxed`](Align4Own::into_boxed).
/// - The address must be 4-byte-aligned to leave the low 2 bits for metadata.
#[repr(C)]
pub struct Align4Own<T> {
    ptr: Align4Ptr,
    _marker: PhantomData<Align4<T>>,
}

impl<T> Align4Own<T> {
    pub fn from_boxed(ptr: Box<Align4<T>>, meta: Metadata) -> Self {
        let ptr = Box::into_raw(ptr);
        Self {
            ptr: unsafe {
                // Safety: the pointer is fetched from a `Box`.
                Align4Ptr::from_parts(NonNull::new_unchecked(ptr as *mut ()), meta)
            },
            _marker: PhantomData,
        }
    }

    /// Consumes `self` and returns the raw pointer.
    pub fn into_raw(self) -> *mut Align4<T> {
        // Note: Forget the previous one to avoid double-free.
        let this = ManuallyDrop::new(self);
        this.ptr.into_parts().0.as_ptr() as *mut Align4<T>
    }

    /// Consumes `self` and returns the boxed value.
    pub fn into_boxed(self) -> Box<Align4<T>> {
        unsafe { Box::from_raw(self.into_raw()) }
    }

    /// Reinterprets the owned pointer as a different type `U`.
    ///
    /// # Safety
    ///
    /// `U` should have a layout compatible with `T`.
    /// If you are temporarily working with a type that has a different layout,
    /// you must cast it back to the original type before `drop` is called.
    pub unsafe fn cast<U>(self) -> ManuallyDrop<Align4Own<U>> {
        // Note: Forget the previous one to avoid double-free.
        let this = ManuallyDrop::new(self);

        ManuallyDrop::new(Align4Own {
            ptr: this.ptr,
            _marker: PhantomData,
        })
    }

    /// Returns a shared reference to the pointee.
    pub fn borrow(&self) -> Ref<'_, T> {
        let (addr, _) = self.ptr.into_parts();
        let ptr = addr.cast::<Align4<T>>().as_ptr();
        // Safety: Without unsafe (cast), `Align4Own` keeps the pointer valid.
        let ptr = unsafe { NonNull::new_unchecked(&raw mut (*ptr).0) };
        Ref {
            ptr,
            _marker: PhantomData,
        }
    }

    /// Returns a mutable pointer-like reference to the pointee.
    ///
    /// # Safety
    ///
    /// Same as [`borrow`](Align4Own::borrow).
    /// The caller must ensure no other mutable aliases exist.
    pub fn borrow_mut(&mut self) -> Mut<'_, T> {
        let (addr, _) = self.ptr.into_parts();
        let ptr = addr.cast::<Align4<T>>().as_ptr();
        // Safety: Without unsafe (cast), `Align4Own` keeps the pointer valid.
        let ptr = unsafe { NonNull::new_unchecked(&raw mut (*ptr).0) };
        Mut {
            ptr,
            _marker: PhantomData,
        }
    }
}

impl<T> Drop for Align4Own<T> {
    fn drop(&mut self) {
        unsafe {
            let _ = Box::from_raw(self.ptr.into_parts().0.as_ptr() as *mut Align4<T>);
        }
    }
}

unsafe impl<T> Send for Align4Own<T> where T: Send {}
unsafe impl<T> Sync for Align4Own<T> where T: Sync {}

/// Shared reference with metadata stored in the low 2 bits of the first byte of the pointer.
///
/// # Safety invariants
///
/// Same as [`Align4Own`]: the address must be 4-byte-aligned and point to a valid `T`.
#[derive(Clone, Copy)]
#[repr(C)]
pub struct Align4Ref<'a, T> {
    ptr: Align4Ptr,
    _marker: PhantomData<&'a Align4<T>>,
}

impl<'a, T> Align4Ref<'a, T> {
    pub fn new(ref_: &'a Align4<T>, meta: Metadata) -> Align4Ref<'a, T> {
        Self {
            ptr: unsafe {
                // Safety: the pointer is fetched from a reference.
                Align4Ptr::from_parts(NonNull::new_unchecked((&raw const *ref_) as *mut ()), meta)
            },
            _marker: PhantomData,
        }
    }

    /// Returns a shared reference to the pointee.
    ///
    /// # Safety
    ///
    /// The stored address must point to a valid, initialized `T`.
    pub fn borrow(&self) -> Ref<'a, T> {
        let (addr, _) = self.ptr.into_parts();
        let ptr = addr.cast::<Align4<T>>().as_ptr();
        // Safety: Without unsafe (cast), `Align4Own` keeps the pointer valid.
        let ptr = unsafe { NonNull::new_unchecked(&raw mut (*ptr).0) };
        Ref {
            ptr,
            _marker: PhantomData,
        }
    }

    pub fn borrow_raw(&self) -> Ref<'a, Align4<T>> {
        let (addr, _) = self.ptr.into_parts();
        let ptr = addr.cast::<Align4<T>>();
        Ref {
            ptr,
            _marker: PhantomData,
        }
    }
}

unsafe impl<'a, T> Send for Align4Ref<'a, T> where T: Send {}
unsafe impl<'a, T> Sync for Align4Ref<'a, T> where T: Sync {}

/// Typed shared reference wrapping a [`NonNull`] pointer.
///
/// Designed for safe field projection via [`Ref::deref`] and [`Ref::project`].
pub struct Ref<'a, T> {
    ptr: NonNull<T>,
    _marker: PhantomData<&'a Align4<T>>,
}

impl<'a, T> Ref<'a, T> {
    /// Reinterprets the reference as a different type `U`.
    ///
    /// # Safety
    ///
    /// `T` and `U` must have the same layout.
    pub unsafe fn cast<U>(self) -> Ref<'a, U> {
        Ref {
            ptr: self.ptr.cast::<U>(),
            _marker: PhantomData,
        }
    }

    /// Projects to a field of `T` using the given offset function.
    ///
    /// # Safety
    ///
    /// `f` must return a pointer that is derived from the input pointer
    /// (i.e., pointing within the same allocation) and must be properly aligned for `F`.
    /// The resulting reference must not violate aliasing rules.
    pub unsafe fn project<F>(self, f: fn(*const T) -> *const F) -> Ref<'a, F> {
        Ref {
            ptr: unsafe { NonNull::new_unchecked(f(self.ptr.as_ptr()).cast_mut()) },
            _marker: PhantomData,
        }
    }

    /// Dereferences to a shared reference.
    ///
    /// # Safety
    ///
    /// The caller must ensure the pointer is valid, properly aligned, and dereferenceable
    /// for the lifetime `'a`.
    pub fn deref(&self) -> &'a T {
        unsafe { self.ptr.as_ref() }
    }
}

impl<'a, T> Ref<'a, T>
where
    T: Copy,
{
    /// Reads the value by copy.
    ///
    /// # Safety
    ///
    /// The pointer must be valid, properly aligned, and dereferenceable.
    pub fn copied(&self) -> T {
        unsafe { self.ptr.read() }
    }
}

impl<'a, T> Clone for Ref<'a, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'a, T> Copy for Ref<'a, T> {}

/// Typed mutable reference wrapping a [`NonNull`] pointer.
///
/// Designed for safe field projection via [`Mut::deref_mut`] and [`Mut::project`].
pub struct Mut<'a, T> {
    ptr: NonNull<T>,
    _marker: PhantomData<&'a mut Align4<T>>,
}

impl<'a, T> Mut<'a, T> {
    /// Reinterprets the mutable reference as a different type `U`.
    ///
    /// # Safety
    ///
    /// `T` and `U` must have the same layout.
    pub unsafe fn cast<U>(self) -> Mut<'a, U> {
        Mut {
            ptr: self.ptr.cast::<U>(),
            _marker: PhantomData,
        }
    }

    /// Projects to a field of `T` using the given offset function.
    ///
    /// # Safety
    ///
    /// `f` must return a pointer that is derived from the input pointer
    /// (i.e., pointing within the same allocation) and must be properly aligned for `F`.
    /// The resulting reference must not violate aliasing rules (e.g., no overlapping borrows).
    #[allow(dead_code)]
    pub unsafe fn project<F>(self, f: fn(*mut T) -> *mut F) -> Mut<'a, F> {
        Mut {
            ptr: unsafe { NonNull::new_unchecked(f(self.ptr.as_ptr())) },
            _marker: PhantomData,
        }
    }

    #[allow(dead_code)]
    pub fn reborrow(&mut self) -> Ref<'_, T> {
        Ref {
            ptr: self.ptr,
            _marker: PhantomData,
        }
    }

    #[allow(dead_code)]
    pub fn reborrow_mut(&mut self) -> Mut<'_, T> {
        Mut {
            ptr: self.ptr,
            _marker: PhantomData,
        }
    }

    /// Dereferences to a mutable reference.
    ///
    /// # Safety
    ///
    /// The caller must ensure the pointer is valid, properly aligned, and dereferenceable
    /// for the lifetime `'a`.
    pub fn deref_mut(mut self) -> &'a mut T {
        unsafe { self.ptr.as_mut() }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use core::mem;

    /// Verifies that `Align4Ptr::from_parts` / `into_parts` round-trips address and metadata.
    #[test]
    fn align4_ptr_round_trip() {
        let value = Align4(0u32); // 4-byte-aligned, low 2 bits are 00
        let addr = NonNull::new(&raw const value as *mut ()).unwrap();
        for meta in [Metadata::_0, Metadata::_1, Metadata::_2, Metadata::_3] {
            let ptr = Align4Ptr::from_parts(addr, meta);
            let (restored_addr, restored_meta) = ptr.into_parts();
            assert_eq!(restored_addr, addr);
            assert_eq!(restored_meta, meta);
        }
    }

    /// Verifies that Align4Ptr panics when the address has non-zero low bits.
    #[test]
    #[should_panic]
    fn align4_ptr_panics_on_unaligned() {
        let bytes: [u8; 2] = [0, 0];
        for i in 0..2 {
            let unaligned = NonNull::new(&raw const bytes[i] as *mut ()).unwrap();
            Align4Ptr::from_parts(unaligned, Metadata::_0);
        }
    }

    /// Verifies that `Align4Own` round-trips a boxed value.
    #[test]
    fn align4_own_boxed_round_trip() {
        let value = Box::new(Align4(42u32));
        let owned = Align4Own::from_boxed(value, Metadata::_1);
        let restored = owned.into_boxed();
        assert_eq!(restored.0, 42);
    }

    /// Verifies that `Align4Own::cast` only changes the type parameter without data loss.
    #[test]
    fn align4_own_cast_preserves_data() {
        let value = Box::new(Align4(0xABCD_EF01u32));
        let owned = Align4Own::from_boxed(value, Metadata::_2);
        // Cast to the same-layout type `[u8; 4]`
        let casted = unsafe { owned.cast::<[u8; 4]>() };
        assert_eq!(casted.borrow().copied(), [0x01, 0xEF, 0xCD, 0xAB]);

        ManuallyDrop::into_inner(unsafe { (ManuallyDrop::into_inner(casted)).cast::<u32>() });
    }

    /// Verifies that `Ref::deref` returns a valid reference.
    #[test]
    fn ref_deref_valid() {
        let value = Box::new(Align4(99u64));
        let owned = Align4Own::from_boxed(value, Metadata::_0);
        let r = owned.borrow();
        assert_eq!(*r.deref(), 99);
    }

    /// Verifies that `Ref::project` correctly accesses a struct field.
    #[test]
    fn ref_project_field() {
        #[repr(C)]
        struct Pair {
            x: u32,
            y: u32,
        }
        let value = Box::new(Align4(Pair { x: 10, y: 20 }));
        let owned = Align4Own::from_boxed(value, Metadata::_0);
        let r = owned.borrow();
        let y_ref = unsafe { r.project(|p| &raw const (*p).y) };
        assert_eq!(*y_ref.deref(), 20);
    }

    /// `Align4<T>` ensures 4-byte alignment.
    #[test]
    fn align4_guarantees_alignment() {
        assert!(mem::align_of::<Align4<u8>>() >= 4);
        assert!(mem::align_of::<Align4<u64>>() >= 4);
    }

    // ------------------------------------------------------------------
    // Align4PtrCompat extreme layout tests
    // ------------------------------------------------------------------

    /// Maximum byte array (`[u8; store_size]`, align 1) fits in the store
    /// and can be read back safely (no alignment issues for byte-slices).
    #[test]
    fn align4_ptr_compat_max_u8_array() {
        const N: usize = cfg_select! {
            target_pointer_width = "64" => 7,
            target_pointer_width = "32" => 3,
            target_pointer_width = "16" => 1,
        };
        let Ok(v) = Align4PtrCompat::<[u8; N]>::new(Metadata::_0, [0xAB; N]) else {
            panic!("max u8 array should fit");
        };
        assert_eq!(v.borrow_value(), &[0xAB; N]);
    }

    /// One byte past the limit — `[u8; store_size + 1]` (align 1) is too large.
    #[test]
    fn align4_ptr_compat_u8_array_one_too_many() {
        const N: usize = cfg_select! {
            target_pointer_width = "64" => 8,
            target_pointer_width = "32" => 4,
            target_pointer_width = "16" => 2,
        };
        assert!(Align4PtrCompat::<[u8; N]>::offset_in_store().is_none());
    }

    /// `u16` — alignment 2, can be stored (store_offset is Some).
    #[test]
    fn align4_ptr_compat_u16_store_offset() {
        assert!(Align4PtrCompat::<u8>::offset_in_store().is_some());
    }

    /// `u32` — alignment 4, can be stored on 64 bit platforms only.
    #[test]
    fn align4_ptr_compat_u32_store_offset() {
        if cfg!(target_pointer_width = "64") {
            assert!(Align4PtrCompat::<u32>::offset_in_store().is_some());
        } else {
            assert!(Align4PtrCompat::<u32>::offset_in_store().is_none());
        }
    }

    /// `u64` — alignment 8, too large for the store buffer on all platforms.
    #[test]
    fn align4_ptr_compat_u64_is_oversized() {
        assert!(Align4PtrCompat::<u64>::offset_in_store().is_none());
    }

    /// Verify that `new()` succeeds and the metadata byte is preserved.
    #[test]
    fn align4_ptr_compat_new_preserves_meta() {
        // Use [u8; 1] (align 1, no alignment issue) to verify meta round-trip.
        let Ok(v) = Align4PtrCompat::<[u8; 1]>::new(Metadata::_3, [0x42]) else {
            panic!("[u8; 1] should fit");
        };
        assert_eq!(*v.borrow_value(), [0x42]);
    }

    /// Creating a type that is too large returns Err with the value.
    #[test]
    fn align4_ptr_compat_new_returns_err_for_oversized() {
        const N: usize = if cfg!(target_pointer_width = "64") {
            8
        } else {
            4
        };
        let value = [0x42u8; N];
        let result = Align4PtrCompat::<[u8; N]>::new(Metadata::_0, value);
        assert!(result.is_err());
    }
}