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
//! InlineDyn
#![allow(clippy::let_unit_value)]
#![cfg_attr(
    feature = "nightly",
    feature(unsize, coerce_unsized, doc_auto_cfg, ptr_metadata)
)]
#![cfg_attr(all(feature = "nightly", feature = "alloc"), feature(allocator_api))]
#![cfg_attr(not(any(feature = "std", test)), no_std)]
#[cfg(feature = "alloc")]
extern crate alloc as std_alloc;
use core::{
    fmt::{Debug, Display, Formatter, Result as FmtResult},
    iter::FusedIterator,
    marker::PhantomData,
    mem::{self, ManuallyDrop, MaybeUninit},
    ops::{Deref, DerefMut},
    pin::Pin,
    ptr,
};

use cfg_if::cfg_if;
use static_assertions::{assert_impl_all, assert_not_impl_any};

use self::pointee::Metadata;
use self::storage::RawStorage;

assert_impl_all!(InlineDyn<dyn Debug + Unpin>: Unpin);
assert_impl_all!(InlineDyn<dyn Debug + Send>: Send);
assert_impl_all!(InlineDyn<dyn Debug + Sync>: Sync);
assert_not_impl_any!(InlineDyn<dyn Debug>: Unpin, Send, Sync);

#[cfg(feature = "nightly")]
mod nightly;
mod pointee;
mod storage;

pub use storage::{Align, Alignment, DEFAULT_SIZE};

struct AssertLayoutCompatible<T, const SIZE: usize, const ALIGN: usize>(PhantomData<T>);

impl<T, const SIZE: usize, const ALIGN: usize> AssertLayoutCompatible<T, SIZE, ALIGN> {
    const OK: () = assert!(
        (mem::size_of::<T>() <= SIZE) && (mem::align_of::<T>() <= ALIGN),
        "size and/or alignment insufficient to store value"
    );
}

struct AssertLarger<const X: usize, const Y: usize>;

impl<const X: usize, const Y: usize> AssertLarger<X, Y> {
    const OK: () = assert!(X >= Y, "new value must not be smaller than old");
}

/// A container type that stores a dynamically-sized type (e.g., a trait object)
/// inline within the container.
///
/// The `S` and `A` generic parameters specify the size and alignment (in bytes)
/// of the internal storage. The default size is the size of a pointer and the
/// alignment defaults to the specified size.
///
/// # Examples
/// ```
/// use inline_dyn::fmt::InlineDynDisplay;
///
/// let val = <InlineDynDisplay>::new(42u8);
/// assert_eq!(val.to_string(), "42");
/// ```
///
/// Insufficient size:
/// ```compile_fail
/// # use inline_dyn::fmt::InlineDynDisplay;
/// let val = InlineDynDisplay<1>::new(42u32);
/// ```
///
/// Insufficient alignment:
/// ```compile_fail
/// # use inline_dyn::fmt::InlineDynDisplay;
/// let val = InlineDynDisplay<4, 1>::new(42u32);
/// ```
pub struct InlineDyn<D: ?Sized, const S: usize = DEFAULT_SIZE, const A: usize = S>
where
    Align<A>: Alignment,
{
    metadata: Metadata<D>,
    storage: RawStorage<S, A>,
    _marker: PhantomData<D>,
}

impl<D: ?Sized, const S: usize, const A: usize> Drop for InlineDyn<D, S, A>
where
    Align<A>: Alignment,
{
    fn drop(&mut self) {
        unsafe {
            (self.get_mut() as *mut D).drop_in_place();
        }
    }
}

impl<D: ?Sized, const S: usize, const A: usize> InlineDyn<D, S, A>
where
    Align<A>: Alignment,
{
    /// # Safety
    /// The caller must guarantee that the provided function returns a pointer
    /// to the specified value, which is a valid instance of type `D`.
    #[doc(hidden)]
    #[cfg(not(feature = "nightly"))]
    pub unsafe fn with_cast<T>(value: T, cast: fn(*const T) -> *const D) -> Self {
        let metadata = Metadata::new(unsafe { mem::transmute(cast) });
        unsafe { Self::with_metadata(metadata, value) }
    }

    /// # Safety
    /// The caller must guarantee that the provided function returns a pointer
    /// to the specified value, which is a valid instance of type `D`.
    #[doc(hidden)]
    #[cfg(not(feature = "nightly"))]
    pub unsafe fn try_with_cast<T>(value: T, cast: fn(*const T) -> *const D) -> Result<Self, T> {
        let metadata = Metadata::new(unsafe { mem::transmute(cast) });
        unsafe { Self::try_with_metadata(metadata, value) }
    }

    /// # Safety
    /// The caller must guarantee that the provided metadata can be soundly used
    /// to convert references to `value` to references to type `D`.
    unsafe fn with_metadata<T>(metadata: Metadata<D>, val: T) -> Self {
        let () = AssertLayoutCompatible::<T, S, A>::OK;
        // SAFETY: the layout has been checked and the validity of the metadata
        // is a precondition of the function.
        unsafe { Self::with_metadata_unchecked(metadata, val) }
    }

    /// # Safety
    /// The caller must guarantee that the provided metadata can be soundly used
    /// to convert references to `value` to references to type `D`.
    unsafe fn try_with_metadata<T>(metadata: Metadata<D>, val: T) -> Result<Self, T> {
        if RawStorage::<S, A>::is_layout_compatible::<T>(&val) {
            // SAFETY: the layout has been checked and the validity of the metadata
            // is a precondition of the function.
            unsafe { Ok(Self::with_metadata_unchecked(metadata, val)) }
        } else {
            Err(val)
        }
    }

    /// # Safety
    /// The caller must guarantee that the provided metadata can be soundly used
    /// to convert references to `value` to references to type `D` and that
    /// the internal storage is layout compatiple with type `T`.
    unsafe fn with_metadata_unchecked<T>(metadata: Metadata<D>, val: T) -> Self {
        let mut storage = RawStorage::new();
        // SAFETY: the layout of the storage being sufficient to write a
        // value of type `T` to is a precondition of the function.
        unsafe {
            storage.as_mut_ptr().cast::<T>().write(val);
        }
        Self {
            metadata,
            storage,
            _marker: PhantomData,
        }
    }

    /// Returns a shared reference to the stored value.
    pub fn get_ref(&self) -> &D {
        // SAFETY: the constructors for `InlineDyn` guarantee that storage is
        // always initialized and that `self.metadata` is appropriate for the
        // stored value.
        unsafe { &*pointee::from_raw_parts(self.storage.as_ptr().cast(), self.metadata) }
    }

    /// Returns a mutable reference to the stored value.
    pub fn get_mut(&mut self) -> &mut D {
        // SAFETY: same as `get_ref`.
        unsafe {
            &mut *pointee::from_raw_parts_mut(self.storage.as_mut_ptr().cast(), self.metadata)
        }
    }

    /// Returns a pinned reference to the stored value.
    pub fn get_pinned_mut(self: Pin<&mut Self>) -> Pin<&mut D> {
        // SAFETY: if `self` is pinned then the contained value is also pinned.
        unsafe { self.map_unchecked_mut(|x| x.get_mut()) }
    }

    /// # Safety
    /// The caller must guarantee that the layout of the resulting storage is
    /// compatible with the contained value.
    unsafe fn resize_unchecked<const U: usize, const V: usize>(this: Self) -> InlineDyn<D, U, V>
    where
        Align<V>: Alignment,
    {
        let size = mem::size_of_val(this.get_ref());
        let this = ManuallyDrop::new(this);
        let mut storage = RawStorage::<U, V>::new();
        // SAFETY: the data is non-overlapping and the layout is a precondition.
        unsafe {
            this.storage
                .as_ptr()
                .copy_to_nonoverlapping(storage.as_mut_ptr(), size);
        }
        InlineDyn {
            metadata: this.metadata,
            storage,
            _marker: PhantomData,
        }
    }

    /// Attempts to move the value contained in `this` into a new [`InlineDyn`]
    /// with the given size (`U`) and alignment (`V`).
    ///
    /// The size and alignment must be large enough to store the contained
    /// value, otherwise `this` is returned.
    ///
    /// # Examples
    /// ```
    /// # use inline_dyn::fmt::InlineDynDisplay;
    /// let val = InlineDynDisplay::new(42u8);
    /// let val: InlineDynDisplay<1> = <InlineDynDisplay>::try_resize(val).ok().unwrap();
    /// assert_eq!(val.to_string(), "42");
    /// ```
    ///
    /// Insufficient size/alignment:
    /// ```
    /// # use inline_dyn::fmt::InlineDynDisplay;
    /// let val = InlineDynDisplay::new(42u32);
    /// let val: Result<InlineDynDisplay<1>, _> = <InlineDynDisplay>::try_resize(val);
    /// assert!(val.is_err());
    /// ```
    pub fn try_resize<const U: usize, const V: usize>(
        this: Self,
    ) -> Result<InlineDyn<D, U, V>, Self>
    where
        Align<V>: Alignment,
    {
        if RawStorage::<U, V>::is_layout_compatible::<D>(this.get_ref()) {
            // SAFETY: the layout has been checked.
            unsafe { Ok(Self::resize_unchecked(this)) }
        } else {
            Err(this)
        }
    }

    /// Moves the value contained in `this` into a new [`InlineDyn`] with the
    /// given size (`U`), and alignment (`V`).
    ///
    /// The size and alignment must be at least as large as the current,
    /// otherwise a compiler error is emitted.
    pub fn grow<const U: usize, const V: usize>(this: Self) -> InlineDyn<D, U, V>
    where
        Align<V>: Alignment,
    {
        let () = AssertLarger::<U, S>::OK;
        let () = AssertLarger::<V, A>::OK;
        // SAFETY: the size and alignment have been checked.
        unsafe { Self::resize_unchecked(this) }
    }
}

impl<D: Unpin + ?Sized, const S: usize, const A: usize> Unpin for InlineDyn<D, S, A> where
    Align<A>: Alignment
{
}

impl<D: ?Sized, const S: usize, const A: usize> Deref for InlineDyn<D, S, A>
where
    Align<A>: Alignment,
{
    type Target = D;

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

impl<D: ?Sized, const S: usize, const A: usize> DerefMut for InlineDyn<D, S, A>
where
    Align<A>: Alignment,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.get_mut()
    }
}

impl<D: Debug + ?Sized, const S: usize, const A: usize> Debug for InlineDyn<D, S, A>
where
    Align<A>: Alignment,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        Debug::fmt(self.get_ref(), f)
    }
}

impl<D: Display + ?Sized, const S: usize, const A: usize> Display for InlineDyn<D, S, A>
where
    Align<A>: Alignment,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        Display::fmt(self.get_ref(), f)
    }
}

/// A trait for cloning trait objects dynamically.
///
/// # Safety
///
/// An implementation must ensure that a valid value of the same type as the
/// implementor is written to the storage passed to `dyn_clone_into`.
///
/// # Examples
///
/// ```
/// use core::fmt::Display;
/// use inline_dyn::{DynClone, dyn_star, inline_dyn};
///
/// trait DynValue: DynClone + Display {}
/// impl<T: Clone + Display> DynValue for T {}
///
/// let val: dyn_star!(DynValue) = inline_dyn![5u8];
/// let val2 = val.clone();
/// assert_eq!(val2.to_string(), "5");
/// ```
pub unsafe trait DynClone {
    #[doc(hidden)]
    fn dyn_clone_into(&self, storage: &mut [MaybeUninit<u8>]);
}

unsafe impl<T> crate::DynClone for T
where
    T: Clone,
{
    /// Writes a copy of the value into `storage`.
    fn dyn_clone_into(&self, storage: &mut [MaybeUninit<u8>]) {
        assert!(mem::size_of::<Self>() <= storage.len());
        let this = (*self).clone();
        unsafe {
            storage.as_mut_ptr().cast::<T>().write(this);
        }
    }
}

impl<D: DynClone + ?Sized, const S: usize, const A: usize> Clone for InlineDyn<D, S, A>
where
    Align<A>: Alignment,
{
    fn clone(&self) -> Self {
        use core::slice;

        let mut storage = RawStorage::new();
        // SAFETY: The implementation requirement for `DynClone` ensures a valid
        // value of the same type as the current value is written to `storage`,
        // so the metadata and storage layout are already known to be correct.
        unsafe {
            self.get_ref()
                .dyn_clone_into(slice::from_raw_parts_mut(storage.as_mut_ptr(), S));
            Self {
                storage,
                metadata: self.metadata,
                _marker: PhantomData,
            }
        }
    }
}

/// A convenience macro that allows for using similar syntax to the proposed
/// [`dyn* Trait`] feature.
///
/// It can be used as a type alias for an [`InlineDyn`] of the specified trait
/// with pointer sized storage.
///
/// [`dyn* Trait`]: https://github.com/rust-lang/rust/issues/102425
#[macro_export]
macro_rules! dyn_star {
    ($($trait:path),+ $(,)?) => {
        $crate::InlineDyn::<dyn ($($trait)*)>
    };
    ($($trait:path,)+ $l:lifetime $(,)?) => {
        $crate::InlineDyn::<dyn $($trait)* + $l>
    };
}

cfg_if! {
    if #[cfg(feature = "nightly")] {
        /// Constructs a new [`InlineDyn`] containing the given value.
        ///
        /// The size and alignment of the internal storage must be large enough
        /// to store the given value, otherwise a compiler error is emitted.
        ///
        /// # Examples
        /// ```
        /// use inline_dyn::{fmt::InlineDynDisplay, inline_dyn};
        ///
        /// let val: InlineDynDisplay = inline_dyn![42usize];
        /// assert_eq!(val.to_string(), "42");
        /// ```
        ///
        /// Trait not implemented:
        /// ```compile_fail
        /// use inline_dyn::{hash::InlineDynHasher, inline_dyn};
        /// let value: InlineDynHasher = inline_dyn![5u8];
        /// ```
        #[macro_export]
        macro_rules! inline_dyn {
            ($e:expr) => {
                $crate::InlineDyn::new($e)
            };
        }
        #[macro_export]
        macro_rules! inline_dyn_try {
            ($e:expr) => {
                $crate::InlineDyn::try_new($e)
            };
        }

        #[cfg(feature = "alloc")]
        #[macro_export]
        macro_rules! inline_dyn_box {
            ($e:expr) => {
                $crate::InlineDyn::try_or_box($e)
            };
        }
    } else {
        /// Constructs a new [`InlineDyn`] containing the given value.
        ///
        /// The size and alignment of the internal storage must be large enough to
        /// store the given value, otherwise a compiler error is emitted.
        ///
        /// # Examples
        /// ```
        /// use inline_dyn::{fmt::InlineDynDisplay, inline_dyn};
        ///
        /// let val: InlineDynDisplay = inline_dyn![42usize];
        /// assert_eq!(val.to_string(), "42");
        /// ```
        ///
        /// Trait not implemented:
        /// ```compile_fail
        /// use inline_dyn::{hash::InlineDynHasher, inline_dyn};
        /// let value: InlineDynHasher = inline_dyn![5u8];
        /// ```
        #[macro_export]
        macro_rules! inline_dyn {
            ($e:expr) => {{
                let value = $e;
                // SAFETY: the lambda acts as witness that the type of the value
                // is coercible to the target type.
                unsafe {
                    $crate::InlineDyn::with_cast(value, |p| p)
                }
            }};
        }

        #[macro_export]
        macro_rules! inline_dyn_try {
            ($e:expr) => {{
                let value = $e;
                // SAFETY: the lambda acts as witness that the type of the value
                // is coercible to the target type.
                unsafe {
                    $crate::InlineDyn::try_with_cast(value, |p| p)
                }
            }};
        }

        #[cfg(feature = "alloc")]
        #[macro_export]
        macro_rules! inline_dyn_box {
            ($e:expr) => {{
                $crate::inline_dyn_try!($e).unwrap_or_else(|v| $crate::inline_dyn!(Box::new(v)))
            }};
        }

        impl<T, const S: usize, const A: usize> InlineDyn<[T], S, A>
        where
            Align<A>: Alignment,
        {
            /// Constructs a new [`InlineDyn`] containing the given value.
            ///
            /// The size and alignment of the internal storage must be large
            /// enough to store the given value, otherwise a compiler error is
            /// emitted.
            ///
            /// # Examples
            /// Insufficient size:
            /// ```compile_fail
            /// InlineDyn::<[u8], 2>::new([1, 2, 3, 4]);
            /// ```
            ///
            /// Insufficient alignment:
            /// ```compile_fail
            /// InlineDyn::<[u32], 16, 2>::new([1, 2, 3, 4]);
            /// ```
            pub fn new<const N: usize>(value: [T; N]) -> Self {
                unsafe { Self::with_cast(value, |p| p) }
            }
        }
    }
}

macro_rules! impl_new {
    ($trait:path $(, $arg:ident)*) => {
        #[cfg(not(feature = "nightly"))]
        impl<'a, const _S: usize, const _A: usize $(, $arg)*> $crate::InlineDyn<(dyn $trait + 'a), _S, _A>
        where $crate::Align<_A>: $crate::Alignment {
            pub fn new<_T: $trait + 'a>(value: _T) -> Self {
                inline_dyn!(value)
            }

            pub fn try_new<_T: $trait + 'a>(value: _T) -> Result<Self, _T> {
                inline_dyn_try!(value)
            }

            #[cfg(feature = "alloc")]
            pub fn try_or_box<_T>(value: _T) -> Self
            where _T: $trait + 'a, std_alloc::boxed::Box<_T>: $trait + 'a, {
                Self::try_new(value).unwrap_or_else(|v| Self::new(std_alloc::boxed::Box::new(v)))
            }
        }
    };
}

impl<T, const S: usize, const A: usize, const N: usize> TryFrom<InlineDyn<[T], S, A>> for [T; N]
where
    Align<A>: Alignment,
{
    type Error = InlineDyn<[T], S, A>;

    fn try_from(value: InlineDyn<[T], S, A>) -> Result<Self, Self::Error> {
        if value.len() != N {
            return Err(value);
        }
        let value = ManuallyDrop::new(value);
        // SAFETY: The value has been wrapped in a `ManuallyDrop` and
        // the length of the slice has been checked.
        unsafe { Ok(value.as_ptr().cast::<[T; N]>().read()) }
    }
}

// impl<T, const S: usize, const A: usize> IntoIterator for InlineDyn<[T], S, A>
// where
//     Align<A>: Alignment,
// {
//     type Item = T;
//     type IntoIter = IntoIter<T, S, A>;

//     fn into_iter(self) -> Self::IntoIter {
//         IntoIter {
//             storage: ManuallyDrop::new(self),
//             pos: 0,
//         }
//     }
// }

pub struct IntoIter<T, const S: usize, const A: usize>
where
    Align<A>: Alignment,
{
    storage: ManuallyDrop<InlineDyn<[T], S, A>>,
    pos: usize,
}

impl<T, const S: usize, const A: usize> Drop for IntoIter<T, S, A>
where
    Align<A>: Alignment,
{
    fn drop(&mut self) {
        unsafe {
            ptr::drop_in_place(&mut self.storage[self.pos..]);
        }
    }
}

impl<T, const S: usize, const A: usize> IntoIter<T, S, A>
where
    Align<A>: Alignment,
{
    pub fn new(inner: InlineDyn<[T], S, A>) -> Self {
        Self {
            storage: ManuallyDrop::new(inner),
            pos: 0,
        }
    }
}

impl<T, const S: usize, const A: usize> Iterator for IntoIter<T, S, A>
where
    Align<A>: Alignment,
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.pos < self.storage.len() {
            let ret = unsafe { self.storage.as_ptr().add(self.pos).read() };
            self.pos += 1;
            Some(ret)
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let left = self.storage.len() - self.pos;
        (left, Some(left))
    }
}

impl<T, const S: usize, const A: usize> ExactSizeIterator for IntoIter<T, S, A> where
    Align<A>: Alignment
{
}

impl<T, const S: usize, const A: usize> FusedIterator for IntoIter<T, S, A> where Align<A>: Alignment
{}

#[cfg(all(feature = "nightly", feature = "alloc"))]
pub mod alloc {
    use core::{
        alloc::{AllocError, Allocator, Layout},
        ptr::NonNull,
    };

    use crate::{Align, Alignment, InlineDyn, DEFAULT_SIZE};

    pub type InlineDynAllocator<const S: usize = DEFAULT_SIZE, const A: usize = S> =
        InlineDyn<dyn Allocator, S, A>;

    unsafe impl<D, const S: usize, const A: usize> Allocator for InlineDyn<D, S, A>
    where
        D: Allocator,
        Align<A>: Alignment,
    {
        fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
            self.get_ref().allocate(layout)
        }

        unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
            // SAFETY: safety of call is a precondition.
            unsafe { self.get_ref().deallocate(ptr, layout) }
        }

        fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
            self.get_ref().allocate_zeroed(layout)
        }

        unsafe fn grow(
            &self,
            ptr: NonNull<u8>,
            old_layout: Layout,
            new_layout: Layout,
        ) -> Result<NonNull<[u8]>, AllocError> {
            // SAFETY: safety of call is a precondition.
            unsafe { self.get_ref().grow(ptr, old_layout, new_layout) }
        }

        unsafe fn grow_zeroed(
            &self,
            ptr: NonNull<u8>,
            old_layout: Layout,
            new_layout: Layout,
        ) -> Result<NonNull<[u8]>, AllocError> {
            // SAFETY: safety of call is a precondition.
            unsafe { self.get_ref().grow_zeroed(ptr, old_layout, new_layout) }
        }

        unsafe fn shrink(
            &self,
            ptr: NonNull<u8>,
            old_layout: Layout,
            new_layout: Layout,
        ) -> Result<NonNull<[u8]>, AllocError> {
            // SAFETY: safety of call is a precondition.
            unsafe { self.get_ref().shrink(ptr, old_layout, new_layout) }
        }
    }
}

pub mod any {
    use core::{
        any::{Any, TypeId},
        mem::ManuallyDrop,
    };

    use crate::{Align, Alignment, InlineDyn, DEFAULT_SIZE};

    pub type InlineDynAny<const S: usize = DEFAULT_SIZE, const A: usize = S> =
        InlineDyn<dyn Any, S, A>;

    #[cfg(not(feature = "nightly"))]
    impl<const S: usize, const A: usize> InlineDynAny<S, A>
    where
        Align<A>: Alignment,
    {
        pub fn new<T: Any>(value: T) -> Self {
            inline_dyn![value]
        }
    }

    impl<D, const S: usize, const A: usize> InlineDyn<D, S, A>
    where
        D: Any + ?Sized,
        Align<A>: Alignment,
    {
        pub fn downcast<T: Any>(self) -> Result<T, Self> {
            if self.get_ref().type_id() == TypeId::of::<T>() {
                let this = ManuallyDrop::new(self);
                // SAFETY: the type id of the stored value has been checked so it is safe to cast
                // and `self` has been wrapped in a `ManuallyDrop`.
                unsafe { Ok((this.get_ref() as *const D).cast::<T>().read()) }
            } else {
                Err(self)
            }
        }
    }
}

pub mod convert {
    use crate::{InlineDyn, DEFAULT_SIZE};

    pub type InlineDynAsRef<'a, U, const S: usize = DEFAULT_SIZE, const A: usize = S> =
        InlineDyn<dyn core::convert::AsRef<U> + 'a, S, A>;
    pub type InlineDynAsMut<'a, U, const S: usize = DEFAULT_SIZE, const A: usize = S> =
        InlineDyn<dyn core::convert::AsMut<U> + 'a, S, A>;

    impl_new!(AsRef<U>, U);
    impl_new!(AsMut<U>, U);
}

pub mod fmt {
    use crate::{InlineDyn, DEFAULT_SIZE};

    pub type InlineDynDebug<'a, const S: usize = DEFAULT_SIZE, const A: usize = S> =
        InlineDyn<dyn core::fmt::Debug + 'a, S, A>;
    pub type InlineDynDisplay<'a, const S: usize = DEFAULT_SIZE, const A: usize = S> =
        InlineDyn<dyn core::fmt::Display + 'a, S, A>;

    impl_new!(core::fmt::Debug);
    impl_new!(core::fmt::Display);
}

pub mod future {
    use crate::{Align, Alignment, InlineDyn, DEFAULT_SIZE};
    use core::{
        future::Future,
        pin::Pin,
        task::{Context, Poll},
    };

    pub type InlineDynFuture<'a, O, const S: usize = DEFAULT_SIZE, const A: usize = S> =
        InlineDyn<dyn Future<Output = O> + 'a, S, A>;

    impl_new!(Future<Output = O>, O);

    impl<F, const S: usize, const A: usize> Future for InlineDyn<F, S, A>
    where
        F: Future + ?Sized,
        Align<A>: Alignment,
    {
        type Output = F::Output;

        fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
            self.get_pinned_mut().poll(cx)
        }
    }
}

pub mod hash {
    use core::hash::Hasher;

    use crate::{Align, Alignment, InlineDyn, DEFAULT_SIZE};

    pub type InlineDynHasher<'a, const S: usize = DEFAULT_SIZE, const A: usize = S> =
        InlineDyn<dyn Hasher + 'a, S, A>;

    impl_new!(Hasher);

    impl<H, const S: usize, const A: usize> Hasher for InlineDyn<H, S, A>
    where
        H: Hasher + ?Sized,
        Align<A>: Alignment,
    {
        fn write(&mut self, bytes: &[u8]) {
            self.get_mut().write(bytes)
        }

        fn finish(&self) -> u64 {
            self.get_ref().finish()
        }
    }
}

pub mod iter {
    use crate::{Align, Alignment, InlineDyn, DEFAULT_SIZE};

    pub type InlineDynIterator<'a, I, const S: usize = DEFAULT_SIZE, const A: usize = S> =
        InlineDyn<dyn Iterator<Item = I> + 'a, S, A>;
    pub type InlineDynDoubleEndedIterator<
        'a,
        I,
        const S: usize = DEFAULT_SIZE,
        const A: usize = S,
    > = InlineDyn<dyn DoubleEndedIterator<Item = I> + 'a, S, A>;

    impl_new!(Iterator<Item = I>, I);
    impl_new!(DoubleEndedIterator<Item = I>, I);

    impl<I, const S: usize, const A: usize> Iterator for InlineDyn<I, S, A>
    where
        I: Iterator + ?Sized,
        Align<A>: Alignment,
    {
        type Item = I::Item;

        fn next(&mut self) -> Option<Self::Item> {
            self.get_mut().next()
        }

        fn size_hint(&self) -> (usize, Option<usize>) {
            self.get_ref().size_hint()
        }

        fn nth(&mut self, n: usize) -> Option<Self::Item> {
            self.get_mut().nth(n)
        }
    }

    impl<I, const S: usize, const A: usize> DoubleEndedIterator for InlineDyn<I, S, A>
    where
        I: DoubleEndedIterator + ?Sized,
        Align<A>: Alignment,
    {
        fn next_back(&mut self) -> Option<Self::Item> {
            self.get_mut().next_back()
        }

        fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
            self.get_mut().nth_back(n)
        }
    }

    impl<I, const S: usize, const A: usize> ExactSizeIterator for InlineDyn<I, S, A>
    where
        I: ExactSizeIterator + ?Sized,
        Align<A>: Alignment,
    {
        fn len(&self) -> usize {
            self.get_ref().len()
        }
    }

    impl<I, const S: usize, const A: usize> core::iter::FusedIterator for InlineDyn<I, S, A>
    where
        I: core::iter::FusedIterator + ?Sized,
        Align<A>: Alignment,
    {
    }
}

pub mod ops {
    #[macro_export]
    macro_rules! InlineDynFn {
        (($($Args:ty),*) $(-> $R:ty)?) => {
            $crate::InlineDynFn!(($($Args),*) $(-> $R)?; $crate::DEFAULT_SIZE)
        };
        (($($Args:ty),*) $(-> $R:ty)?; $S:ty) => {
            $crate::InlineDynFn!(($($Args),*) $(-> $R)?; $S, $S)
        };
        (($($Args:ty),*) $(-> $R:ty)?; $S:ty, $A:ty) => {
            $crate::InlineDyn<dyn Fn($($Args),*)$(-> $R)?, $S, $A>
        };
    }

    #[macro_export]
    macro_rules! InlineDynFnMut {
        (($($Args:ty),*) $(-> $R:ty)?) => {
            $crate::InlineDynFnMut!(($($Args),*) $(-> $R)?; $crate::DEFAULT_SIZE)
        };
        (($($Args:ty),*) $(-> $R:ty)?; $S:ty) => {
            $crate::InlineDyn<dyn FnMut($($Args),*)$(-> $R)?, $S, $S>
        };
        (($($Args:ty),*) $(-> $R:ty)?; $S:ty, $A:ty) => {
            $crate::InlineDyn<dyn FnMut($($Args),*)$(-> $R)?, $S, $A>
        };
    }
}

cfg_if! {
    if #[cfg(feature = "std")] {
        pub mod error {
            use std::error::Error;

            use crate::{Align, Alignment, InlineDyn, DEFAULT_SIZE};

            pub type InlineDynError<'a, const S: usize = DEFAULT_SIZE, const A: usize = S> = InlineDyn<dyn Error + 'a, S, A>;

            impl_new!(Error);

            #[allow(deprecated)]
            impl<E, const S: usize, const A: usize> Error for InlineDyn<E, S, A>
            where
                E: Error + ?Sized,
                Align<A>: Alignment,
            {
                fn description(&self) -> &str {
                    self.get_ref().description()
                }

                fn cause(&self) -> Option<&dyn Error> {
                    self.get_ref().cause()
                }

                fn source(&self) -> Option<&(dyn Error + 'static)> {
                    self.get_ref().source()
                }
            }
        }

        pub mod io {
            use crate::{Align, Alignment, InlineDyn, DEFAULT_SIZE};
            use std::io;

            pub type InlineDynRead<'a, const S: usize = DEFAULT_SIZE, const A: usize = S> = InlineDyn<dyn io::Read + 'a, S, A>;
            pub type InlineDynWrite<'a, const S: usize = DEFAULT_SIZE, const A: usize = S> = InlineDyn<dyn io::Write + 'a, S, A>;
            pub type InlineDynSeek<'a, const S: usize = DEFAULT_SIZE, const A: usize = S> = InlineDyn<dyn io::Seek + 'a, S, A>;
            pub type InlineDynBufRead<'a, const S: usize = DEFAULT_SIZE, const A: usize = S> = InlineDyn<dyn io::BufRead + 'a, S, A>;

            impl_new!(io::Read);
            impl_new!(io::Write);
            impl_new!(io::Seek);
            impl_new!(io::BufRead);

            impl<T, const S: usize, const A: usize> io::Read for InlineDyn<T, S, A>
            where
                T: io::Read + ?Sized,
                Align<A>: Alignment,
            {
                fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
                    self.get_mut().read(buf)
                }

                fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> {
                    self.get_mut().read_vectored(bufs)
                }

                fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
                    self.get_mut().read_exact(buf)
                }
            }

            impl<T, const S: usize, const A: usize> io::Write for InlineDyn<T, S, A>
            where
                T: io::Write + ?Sized,
                Align<A>: Alignment,
            {
                fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                    self.get_mut().write(buf)
                }

                fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
                    self.get_mut().write_vectored(bufs)
                }

                fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
                    self.get_mut().write_all(buf)
                }

                fn flush(&mut self) -> io::Result<()> {
                    self.get_mut().flush()
                }
            }

            impl<T, const S: usize, const A: usize> io::Seek for InlineDyn<T, S, A>
            where
                T: io::Seek + ?Sized,
                Align<A>: Alignment,
            {
                fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
                    self.get_mut().seek(pos)
                }
            }

            impl<T, const S: usize, const A: usize> io::BufRead for InlineDyn<T, S, A>
            where
                T: io::BufRead + ?Sized,
                Align<A>: Alignment,
            {
                fn fill_buf(&mut self) -> io::Result<&[u8]> {
                    self.get_mut().fill_buf()
                }

                fn consume(&mut self, amt: usize) {
                    self.get_mut().consume(amt)
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use core::cell::Cell;

    use super::{fmt::InlineDynDebug, *};

    macro_rules! assert_matches {
        ($left:expr, $(|)? $($pattern:pat_param)|+ $(if $guard:expr)? $(,)?) => {
            match $left {
                $($pattern)|+ $(if $guard)? => {}
                ref left_val => {
                    panic!(r#"assertion failed: `(left matches right)`
                     left: `{left_val:?}`
                    right: `{}`"#, stringify!($($pattern)|+ $(if $guard)?))
                }
            }
        };
    }

    #[test]
    fn test_simple() {
        let val = <dyn_star!(Debug)>::new(42usize);
        assert_eq!(format!("{val:?}"), "42");
    }

    #[test]
    fn test_drop() {
        #[derive(Debug)]
        struct Dropper<'a>(&'a mut bool);

        impl Drop for Dropper<'_> {
            fn drop(&mut self) {
                *self.0 = true;
            }
        }

        let mut dropped = false;
        {
            let dbg = <dyn_star!(Debug, '_)>::new(Dropper(&mut dropped));
            assert_eq!(format!("{dbg:?}"), "Dropper(false)");
        }
        assert!(dropped);
    }

    #[test]
    fn test_resize() {
        let val = <dyn_star!(Debug)>::new(42u8);
        assert_eq!(format!("{val:?}"), "42");

        let val: InlineDynDebug<1> = <dyn_star!(Debug)>::try_resize(val).ok().unwrap();
        assert_eq!(format!("{val:?}"), "42");
    }

    #[test]
    fn test_resize_insufficient() {
        let val = <dyn_star!(Debug)>::new(42u32);
        assert_eq!(format!("{val:?}"), "42");

        let res: Result<InlineDynDebug<1>, _> = <dyn_star!(Debug)>::try_resize(val);
        assert_matches!(res, Err(_));
    }

    #[test]
    fn test_slice() {
        let val = InlineDyn::<[u8], 4>::new([1, 2, 3, 4]);
        assert_eq!(val.get_ref(), [1, 2, 3, 4]);
    }

    #[test]
    fn test_interior_mutability() {
        trait Foo {
            fn foo(&self) -> u32;
        }

        struct Bar(Cell<u32>);

        impl Foo for Bar {
            fn foo(&self) -> u32 {
                let r = self.0.get();
                self.0.set(r + 1);
                r
            }
        }

        let val: dyn_star!(Foo) = inline_dyn![Bar(Cell::new(0))];
        assert_eq!(val.foo(), 0);
        assert_eq!(val.foo(), 1);
        assert_eq!(val.foo(), 2);
    }

    #[test]
    fn test_not_unpin() {
        use super::future::InlineDynFuture;
        use core::{
            future::{poll_fn, Future},
            pin::pin,
            ptr,
            task::{Context, Poll, RawWaker, RawWakerVTable, Waker},
        };

        struct NoopWaker;

        impl From<NoopWaker> for RawWaker {
            fn from(_: NoopWaker) -> Self {
                RawWaker::new(
                    ptr::null(),
                    &RawWakerVTable::new(|_| NoopWaker.into(), |_| (), |_| (), |_| ()),
                )
            }
        }

        impl From<NoopWaker> for Waker {
            fn from(value: NoopWaker) -> Self {
                unsafe { Waker::from_raw(value.into()) }
            }
        }

        async fn delay(mut amt: usize) {
            let amt = &mut amt; // ensure returned future is self-referential
            poll_fn(|cx| {
                cx.waker().wake_by_ref();
                match amt {
                    0 => Poll::Ready(()),
                    _ => {
                        *amt -= 1;
                        Poll::Pending
                    }
                }
            })
            .await
        }

        let waker = Waker::from(NoopWaker);
        let mut cx = Context::from_waker(&waker);
        // 1KiB should be enough for anybody
        let mut fut = pin!(<InlineDynFuture<u32, 1024, 16>>::new(async {
            delay(3).await;
            42
        }));
        assert_matches!(fut.as_mut().poll(&mut cx), Poll::Pending);
        assert_matches!(fut.as_mut().poll(&mut cx), Poll::Pending);
        assert_matches!(fut.as_mut().poll(&mut cx), Poll::Pending);
        assert_matches!(fut.as_mut().poll(&mut cx), Poll::Ready(42));
    }
}