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
#![deny(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
//
#![feature(never_type)]
#![feature(allocator_api)]
#![cfg_attr(
    any(feature = "alloc", feature = "std"),
    feature(new_uninit, get_mut_unchecked)
)]

//! Library to safely and fallibly initialize pinned structs using in-place constructors.
//!
//! It also allows in-place initialization of big structs that would otherwise produce a stack overflow.
//!
//! [Pinning][pinning] is Rust's way of ensuring data does not move.
//!
//! # Overview
//!
//! To initialize a struct with an in-place constructor you will need two things:
//! - an in-place constructor,
//! - a memory location that can hold your struct (this can be the [stack], an [`Arc<T>`],
//!   [`Box<T>`] or any other smart pointer [^1]).
//!
//! To get an in-place constructor there are generally two options:
//! - directly creating an in-place constructor,
//! - a function/macro returning an in-place constructor.
//!
//! # Examples
//!
//! ## Directly creating an in-place constructor
//!
//! If you want to use [`PinInit`], then you will have to annotate your struct with [`#[pin_project]`].
//! It is a macro that uses `#[pin]` as a marker for [structurally pinned fields].
//!
//! ```rust
//! # mod mutex {
//! #     include!("../examples/mutex.rs");
//! # };
//! # use mutex::*;
//! # use core::pin::Pin;
//! # use pinned_init::*;
//! #[pin_project]
//! struct Foo {
//!     #[pin]
//!     a: Mutex<usize>,
//!     b: u32,
//! }
//!
//! let foo = pin_init!(Foo {
//!     a: Mutex::new(42),
//!     b: 24,
//! });
//! # let foo: Result<Pin<Box<Foo>>, _> = Box::pin_init::<core::convert::Infallible>(foo);
//! ```
//!
//! `foo` now is of the type `impl`[`PinInit<Foo>`]. We can now use any smart pointer that we like
//! (or just the stack) to actually initialize a `Foo`:
//!
//! ```rust
//! # mod mutex {
//! #     include!("../examples/mutex.rs");
//! # };
//! # use mutex::*;
//! # use core::pin::Pin;
//! # use pinned_init::*;
//! # #[pin_project]
//! # struct Foo {
//! #     #[pin]
//! #     a: Mutex<usize>,
//! #     b: u32,
//! # }
//! # let foo = pin_init!(Foo {
//! #     a: Mutex::new(42),
//! #     b: 24,
//! # });
//! let foo: Result<Pin<Box<Foo>>, _> = Box::pin_init::<core::convert::Infallible>(foo);
//! ```
//!
//! ## Using a function/macro that returns an initializer
//!
//! Many types using this library supply a function/macro that returns an initializer, because the
//! above method only works for types where you can access the fields.
//!
//! ```rust
//! # mod mutex {
//! #     include!("../examples/mutex.rs");
//! # };
//! # use mutex::*;
//! # use std::{pin::Pin,sync::Arc};
//! # use pinned_init::*;
//! let mtx: Result<Pin<Arc<Mutex<usize>>>, _> = Arc::pin_init(Mutex::new(42));
//! ```
//!
//! To declare an init macro/function you just return an `impl`[`PinInit<T, E>`]:
//! ```rust
//! # mod mutex {
//! #     include!("../examples/mutex.rs");
//! # };
//! # use mutex::*;
//! # use pinned_init::*;
//! # use core::convert::Infallible;
//! #[pin_project]
//! struct DriverData {
//!     #[pin]
//!     status: Mutex<i32>,
//!     buffer: Box<[u8; 1_000_000]>,
//! }
//!
//! impl DriverData {
//!     fn new() -> impl PinInit<Self, AllocOrInitError<Infallible>> {
//!         pin_init!(Self {
//!             status: Mutex::new(0),
//!             buffer: Box::init(pinned_init::zeroed())?,
//!         })
//!     }
//! }
//! ```
//!
//!
//! [^1]: That is not entirely true, only smart pointers that implement [`InPlaceInit`].
//!
//! [pinning]: https://doc.rust-lang.org/std/pin/index.html
//! [structurally pinned fields]: https://doc.rust-lang.org/std/pin/index.html#pinning-is-structural-for-field
//! [stack]: crate::stack_init

#[cfg(feature = "alloc")]
use alloc::alloc::AllocError;
use core::{marker::PhantomData, mem::MaybeUninit, pin::Pin, ptr};
#[cfg(feature = "std")]
use std::alloc::AllocError;

#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::{boxed::Box, rc::Rc, sync::Arc};
#[cfg(all(not(feature = "alloc"), feature = "std"))]
use std::{boxed::Box, rc::Rc, sync::Arc};

use core::convert::Infallible;

#[doc(hidden)]
pub mod __private;
mod pin_project;

/// Initialize a type directly on the stack.
///
/// # Examples
///
/// ```rust
/// # #![allow(clippy::blacklisted_name, clippy::new_ret_no_self)]
/// # mod mutex {
/// #     include!("../examples/mutex.rs");
/// # };
/// # use mutex::*;
/// # use pinned_init::*;
/// # use core::{convert::Infallible,pin::Pin};
/// #[pin_project]
/// struct Foo {
///     #[pin]
///     a: Mutex<usize>,
///     b: Bar,
/// }
///
/// #[pin_project]
/// struct Bar {
///     x: u32,
/// }
///
/// let a = Mutex::new(40);
///
/// stack_init!(let foo = pin_init!(Foo {
///     a,
///     b: Bar {
///         x: 64,
///     },
/// }));
/// let foo: Result<Pin<&mut Foo>, Infallible> = foo;
/// ```
#[macro_export]
macro_rules! stack_init {
    (let $var:ident $(: $t:ty)? = $val:expr) => {
        let mut $var = $crate::__private::StackInit$(::<$t>)?::uninit();
        let val = $val;
        let mut $var = unsafe { $crate::__private::StackInit::init(&mut $var, val) };
    };
}

/// Construct an in-place initializer for structs.
///
/// The syntax is identical to a normal struct initializer:
///
/// ```rust
/// # #![allow(clippy::blacklisted_name, clippy::new_ret_no_self)]
/// # use pinned_init::*;
/// # use core::pin::Pin;
/// #[pin_project]
/// struct Foo {
///     a: usize,
///     b: Bar,
/// }
///
/// #[pin_project]
/// struct Bar {
///     x: u32,
/// }
///
/// # fn demo() -> impl PinInit<Foo> {
/// let a = 42;
///
/// let initializer = pin_init!(Foo {
///     a,
///     b: Bar {
///         x: 64,
///     },
/// });
/// # initializer }
/// # Box::pin_init(demo()).unwrap();
/// ```
/// Arbitrary rust expressions can be used to set the value of a variable.
///
/// # Init-functions
///
/// When working with this library it is often desired to let others construct your types without
/// giving access to all fields. This is where you would normally write a plain function `new`
/// that would return a new instance of your type. With this library that is also possible, however
/// there are a few extra things to keep in mind.
///
/// To create an initializer function, simple declare it like this:
///
/// ```rust
/// # #![allow(clippy::blacklisted_name, clippy::new_ret_no_self)]
/// # use pinned_init::*;
/// # use core::pin::Pin;
/// # #[pin_project]
/// # struct Foo {
/// #     a: usize,
/// #     b: Bar,
/// # }
/// # #[pin_project]
/// # struct Bar {
/// #     x: u32,
/// # }
///
/// impl Foo {
///     fn new() -> impl PinInit<Self> {
///         pin_init!(Self {
///             a: 42,
///             b: Bar {
///                 x: 64,
///             },
///         })
///     }
/// }
/// ```
///
/// Users of `Foo` can now create it like this:
///
/// ```rust
/// # #![allow(clippy::blacklisted_name, clippy::new_ret_no_self)]
/// # use pinned_init::*;
/// # use core::pin::Pin;
/// # #[pin_project]
/// # struct Foo {
/// #     a: usize,
/// #     b: Bar,
/// # }
/// # #[pin_project]
/// # struct Bar {
/// #     x: u32,
/// # }
/// # impl Foo {
/// #     fn new() -> impl PinInit<Self> {
/// #         pin_init!(Self {
/// #             a: 42,
/// #             b: Bar {
/// #                 x: 64,
/// #             },
/// #         })
/// #     }
/// # }
/// let foo = Box::pin_init(Foo::new());
/// ```
///
/// They can also easily embed it into their own `struct`s:
///
/// ```rust
/// # #![allow(clippy::blacklisted_name, clippy::new_ret_no_self)]
/// # use pinned_init::*;
/// # use core::pin::Pin;
/// # #[pin_project]
/// # struct Foo {
/// #     a: usize,
/// #     b: Bar,
/// # }
/// # #[pin_project]
/// # struct Bar {
/// #     x: u32,
/// # }
/// # impl Foo {
/// #     fn new() -> impl PinInit<Self> {
/// #         pin_init!(Self {
/// #             a: 42,
/// #             b: Bar {
/// #                 x: 64,
/// #             },
/// #         })
/// #     }
/// # }
/// #[pin_project]
/// struct FooContainer {
///     #[pin]
///     foo1: Foo,
///     #[pin]
///     foo2: Foo,
///     other: u32,
/// }
///
/// impl FooContainer {
///     fn new(other: u32) -> impl PinInit<Self> {
///         pin_init!(Self {
///             foo1: Foo::new(),
///             foo2: Foo::new(),
///             other,
///         })
///     }
/// }
/// ```
#[macro_export]
macro_rules! pin_init {
    ($(&$this:ident in)? $t:ident $(<$($generics:ty),* $(,)?>)? {
        $($field:ident $(: $val:expr)?),*
        $(,)?
    }) => {
        $crate::pin_init!(@this($($this)?), @type_name($t $(<$($generics),*>)?), @typ($t $(<$($generics),*>)?), @fields($($field $(: $val)?),*))
    };
    (@this($($this:ident)?), @type_name($t:ident $(<$($generics:ty),*>)?), @typ($ty:ty), @fields($($field:ident $(: $val:expr)?),*)) => {{
        // we do not want to allow arbitrary returns
        struct __InitOk;
        let init = move |slot: *mut $ty| -> ::core::result::Result<__InitOk, _> {
            {
                // shadow the structure so it cannot be used to return early
                struct __InitOk;
                $(let $this = unsafe { ::core::ptr::NonNull::new_unchecked(slot) };)?
                $(
                    $(let $field = $val;)?
                    // call the initializer
                    // SAFETY: slot is valid, because we are inside of an initializer closure, we return
                    //         when an error/panic occurs.
                    unsafe {
                        <$ty as $crate::__private::__PinData>::__PinData::$field(
                            ::core::ptr::addr_of_mut!((*slot).$field),
                            $field,
                        )?;
                    }
                    // create the drop guard
                    // SAFETY: we forget the guard later when initialization has succeeded.
                    let $field = unsafe { $crate::__private::DropGuard::new(::core::ptr::addr_of_mut!((*slot).$field)) };
                    // only give access to &DropGuard, so it cannot be accidentally forgotten
                    let $field = &$field;
                )*
                #[allow(unreachable_code, clippy::diverging_sub_expression)]
                if false {
                    let _: $t $(<$($generics),*>)? = $t {
                        $($field: ::core::todo!()),*
                    };
                }
                $(
                    // forget each guard
                    unsafe { $crate::__private::DropGuard::forget($field) };
                )*
            }
            Ok(__InitOk)
        };
        let init = move |slot: *mut $ty| -> ::core::result::Result<(), _> {
            init(slot).map(|__InitOk| ())
        };
        let init = unsafe { $crate::pin_init_from_closure::<$t $(<$($generics),*>)?, _>(init) };
        init
    }}
}

/// Construct an in-place initializer for structs.
///
/// The syntax is identical to a normal struct initializer:
///
/// ```rust
/// # #![allow(clippy::blacklisted_name, clippy::new_ret_no_self)]
/// # use pinned_init::*;
/// # use core::pin::Pin;
/// struct Foo {
///     a: usize,
///     b: Bar,
/// }
///
/// struct Bar {
///     x: u32,
/// }
///
/// # fn demo() -> impl Init<Foo> {
/// let a = 42;
///
/// let initializer = init!(Foo {
///     a,
///     b: Bar {
///         x: 64,
///     },
/// });
/// # initializer }
/// # Box::init(demo()).unwrap();
/// ```
///
/// Arbitrary rust expressions can be used to set the value of a variable.
///
/// # Init-functions
///
/// When working with this library it is often desired to let others construct your types without
/// giving access to all fields. This is where you would normally write a plain function `new`
/// that would return a new instance of your type. With this library that is also possible, however
/// there are a few extra things to keep in mind.
///
/// To create an initializer function, simple declare it like this:
///
/// ```rust
/// # #![allow(clippy::blacklisted_name, clippy::new_ret_no_self)]
/// # use pinned_init::*;
/// # use core::pin::Pin;
/// # struct Foo {
/// #     a: usize,
/// #     b: Bar,
/// # }
/// # struct Bar {
/// #     x: u32,
/// # }
///
/// impl Foo {
///     fn new() -> impl Init<Self> {
///         init!(Self {
///             a: 42,
///             b: Bar {
///                 x: 64,
///             },
///         })
///     }
/// }
/// ```
///
/// Users of `Foo` can now create it like this:
///
/// ```rust
/// # #![allow(clippy::blacklisted_name, clippy::new_ret_no_self)]
/// # use pinned_init::*;
/// # use core::pin::Pin;
/// # struct Foo {
/// #     a: usize,
/// #     b: Bar,
/// # }
/// # struct Bar {
/// #     x: u32,
/// # }
/// # impl Foo {
/// #     fn new() -> impl Init<Self> {
/// #         init!(Self {
/// #             a: 42,
/// #             b: Bar {
/// #                 x: 64,
/// #             },
/// #         })
/// #     }
/// # }
/// let foo = Box::init(Foo::new());
/// ```
///
/// They can also easily embed it into their own `struct`s:
///
/// ```rust
/// # #![allow(clippy::blacklisted_name, clippy::new_ret_no_self)]
/// # use pinned_init::*;
/// # use core::pin::Pin;
/// # struct Foo {
/// #     a: usize,
/// #     b: Bar,
/// # }
/// # struct Bar {
/// #     x: u32,
/// # }
/// # impl Foo {
/// #     fn new() -> impl Init<Self> {
/// #         init!(Self {
/// #             a: 42,
/// #             b: Bar {
/// #                 x: 64,
/// #             },
/// #         })
/// #     }
/// # }
/// struct FooContainer {
///     foo1: Foo,
///     foo2: Foo,
///     other: u32,
/// }
///
/// impl FooContainer {
///     fn new(other: u32) -> impl Init<Self> {
///         init!(Self {
///             foo1: Foo::new(),
///             foo2: Foo::new(),
///             other,
///         })
///     }
/// }
/// ```
#[macro_export]
macro_rules! init {
    ($t:ident $(<$($generics:ty),* $(,)?>)? {
        $($field:ident $(: $val:expr)?),*
        $(,)?
    }) => {{
        // we do not want to allow arbitrary returns
        struct __InitOk;
        let init = move |slot: *mut $t $(<$($generics),*>)?| -> ::core::result::Result<__InitOk, _> {
            {
                // shadow the structure so it cannot be used to return early
                struct __InitOk;
                $(
                    $(let $field = $val;)?
                    // call the initializer
                    // SAFETY: slot is valid, because we are inside of an initializer closure, we return
                    //         when an error/panic occurs.
                    unsafe { $crate::__private::__InitImpl::__init($field, ::core::ptr::addr_of_mut!((*slot).$field))? };
                    // create the drop guard
                    // SAFETY: we forget the guard later when initialization has succeeded.
                    let $field = unsafe { $crate::__private::DropGuard::new(::core::ptr::addr_of_mut!((*slot).$field)) };
                    // only give access to &DropGuard, so it cannot be accidentally forgotten
                    let $field = &$field;
                )*
                #[allow(unreachable_code, clippy::diverging_sub_expression)]
                if false {
                    let _: $t $(<$($generics),*>)? = $t {
                        $($field: ::core::todo!()),*
                    };
                }
                $(
                    // forget each guard
                    unsafe { $crate::__private::DropGuard::forget($field) };
                )*
            }
            Ok(__InitOk)
        };
        let init = move |slot: *mut $t $(<$($generics),*>)?| -> ::core::result::Result<(), _> {
            init(slot).map(|__InitOk| ())
        };
        let init = unsafe { $crate::init_from_closure::<$t $(<$($generics),*>)?, _>(init) };
        init
    }}
}

pub use pinned_init_macro::{pin_project, pinned_drop};

/// A pinned initializer for `T`.
///
/// To use this initializer, you will need a suitable memory location that can hold a `T`. This can
/// be [`Box<T>`], [`Arc<T>`], or even the stack (see [`stack_init!`]). Use the
/// `pin_init` function of a smart pointer like [`Arc::pin_init`] on this.
///
/// Also see the [module description](self).
///
/// # Safety
///
/// When implementing this type you will need to take great care. Also there are probably very few
/// cases where a manual implementation is necessary. Use [`from_value`] and
/// [`pin_init_from_closure`] where possible.
///
/// The [`PinInit::__pinned_init`] function
/// - returns `Ok(())` iff it initialized every field of slot,
/// - returns `Err(err)` iff it encountered an error and then cleaned slot, this means:
///     - slot can be deallocated without UB ocurring,
///     - slot does not need to be dropped,
///     - slot is not partially initialized.
///
#[must_use = "An initializer must be used in order to create its value."]
pub unsafe trait PinInit<T, E = Infallible>: Sized {
    /// Initializes `slot`.
    ///
    /// # Safety
    ///
    /// `slot` is a valid pointer to uninitialized memory.
    /// The caller does not touch `slot` when `Err` is returned, they are only permitted to
    /// deallocate.
    /// The slot will not move, i.e. it will be pinned.
    unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E>;
}

/// An initializer for `T`.
///
/// To use this initializer, you will need a suitable memory location that can hold a `T`. This can
/// be [`Box<T>`], [`Arc<T>`], or even the stack (see [`stack_init!`]). Use the
/// `init` function of a smart pointer like [`Box::init`] on this. Because [`PinInit<T, E>`] is a
/// super trait, you can use every function that takes it as well.
///
/// Also see the [module description](self).
///
/// # Safety
///
/// When implementing this type you will need to take great care. Also there are probably very few
/// cases where a manual implementation is necessary. Use [`from_value`] and
/// [`init_from_closure`] where possible.
///
/// The [`Init::__init`] function
/// - returns `Ok(())` iff it initialized every field of slot,
/// - returns `Err(err)` iff it encountered an error and then cleaned slot, this means:
///     - slot can be deallocated without UB ocurring,
///     - slot does not need to be dropped,
///     - slot is not partially initialized.
///
/// The `__pinned_init` function from the supertrait [`PinInit`] needs to exectute the exact same
/// code as `__init`.
///
/// Contrary to its supertype [`PinInit<T, E>`] the caller is allowed to
/// move the pointee after initialization.
///
#[must_use = "An initializer must be used in order to create its value."]
pub unsafe trait Init<T, E = Infallible>: PinInit<T, E> {
    /// Initializes `slot`.
    ///
    /// # Safety
    ///
    /// `slot` is a valid pointer to uninitialized memory.
    /// The caller does not touch `slot` when `Err` is returned, they are only permitted to
    /// deallocate.
    unsafe fn __init(self, slot: *mut T) -> Result<(), E>;
}

type Invariant<T> = PhantomData<fn(T) -> T>;

struct InitClosure<F, T, E>(F, Invariant<(T, E)>);

unsafe impl<T, F, E> PinInit<T, E> for InitClosure<F, T, E>
where
    F: FnOnce(*mut T) -> Result<(), E>,
{
    unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {
        (self.0)(slot)
    }
}

unsafe impl<T, F, E> Init<T, E> for InitClosure<F, T, E>
where
    F: FnOnce(*mut T) -> Result<(), E>,
{
    unsafe fn __init(self, slot: *mut T) -> Result<(), E> {
        (self.0)(slot)
    }
}

/// Creates a new [`Init<T, E>`] from the given closure.
///
/// # Safety
///
/// The closure
/// - returns `Ok(())` iff it initialized every field of slot,
/// - returns `Err(err)` iff it encountered an error and then cleaned slot, this means:
///     - slot can be deallocated without UB ocurring,
///     - slot does not need to be dropped,
///     - slot is not partially initialized.
/// - slot may move after initialization
pub const unsafe fn init_from_closure<T, E>(
    f: impl FnOnce(*mut T) -> Result<(), E>,
) -> impl Init<T, E> {
    InitClosure(f, PhantomData)
}
/// Creates a new [`PinInit<T, E>`] from the given closure.
///
/// # Safety
///
/// The closure
/// - returns `Ok(())` iff it initialized every field of slot,
/// - returns `Err(err)` iff it encountered an error and then cleaned slot, this means:
///     - slot can be deallocated without UB ocurring,
///     - slot does not need to be dropped,
///     - slot is not partially initialized.
/// - may assume that the slot does not move if `T: !Unpin`
pub const unsafe fn pin_init_from_closure<T, E>(
    f: impl FnOnce(*mut T) -> Result<(), E>,
) -> impl PinInit<T, E> {
    InitClosure(f, PhantomData)
}

/// Trait facilitating pinned destruction.
///
/// Use [`pinned_drop`] to implement this trait safely:
/// ```rust
/// # mod mutex {
/// #     include!("../examples/mutex.rs");
/// # };
/// # use mutex::*;
/// use core::pin::Pin;
/// use pinned_init::*;
/// #[pin_project(PinnedDrop)]
/// struct Foo {
///     #[pin]
///     mtx: Mutex<usize>,
/// }
///
/// #[pinned_drop]
/// impl PinnedDrop for Foo {
///     fn drop(self: Pin<&mut Self>) {
///         println!("Foo is being dropped!");
///     }
/// }
/// ```
///
/// # Safety
///
/// This trait must be implemented with [`pinned_drop`].
pub unsafe trait PinnedDrop {
    /// Executes the pinned destructor of this type.
    ///
    /// # Safety
    ///
    /// Only call this from `<Self as Drop>::drop`.
    unsafe fn drop(self: Pin<&mut Self>);

    // used by `pinned_drop` to ensure that only safe operations are used in `drop`.
    #[doc(hidden)]
    fn __ensure_no_unsafe_op_in_drop(self: Pin<&mut Self>);
}

/// Allocation error, or initialization error.
#[derive(Debug)]
pub enum AllocOrInitError<E> {
    /// Allocation failed.
    AllocError,
    /// Intialization failed.
    Init(E),
}

#[cfg(any(feature = "alloc", feature = "std"))]
impl<E> From<AllocError> for AllocOrInitError<E> {
    fn from(_: AllocError) -> Self {
        Self::AllocError
    }
}
impl<E> From<Infallible> for AllocOrInitError<E> {
    fn from(e: Infallible) -> Self {
        match e {}
    }
}

/// Smart pointer that can initialize memory in-place.
pub trait InPlaceInit<T>: Sized {
    /// The error that might occur when creating `Self`.
    type Error<E>;

    /// Use the given initializer to in-place initialize a `T`.
    ///
    /// If `T: !Unpin` it will not be able to move afterwards.
    fn pin_init<E>(init: impl PinInit<T, E>) -> Result<Pin<Self>, Self::Error<E>>;

    /// Use the given initializer to in-place initialize a `T`.
    fn init<E>(init: impl Init<T, E>) -> Result<Self, Self::Error<E>>;
}

#[cfg(any(feature = "alloc", feature = "std"))]
impl<T> InPlaceInit<T> for Box<T> {
    type Error<E> = AllocOrInitError<E>;

    fn pin_init<E>(init: impl PinInit<T, E>) -> Result<Pin<Self>, Self::Error<E>> {
        let mut this = Box::try_new_uninit()?;
        let slot = this.as_mut_ptr();
        // SAFETY: when init errors/panics, slot will get deallocated but not dropped,
        // slot is valid and will not be moved because of the `Pin::new_unchecked`
        unsafe { init.__pinned_init(slot).map_err(AllocOrInitError::Init)? };
        // SAFETY: all fields have been initialized
        Ok(unsafe { Pin::new_unchecked(this.assume_init()) })
    }

    fn init<E>(init: impl Init<T, E>) -> Result<Self, Self::Error<E>> {
        let mut this = Box::try_new_uninit()?;
        let slot = this.as_mut_ptr();
        // SAFETY: when init errors/panics, slot will get deallocated but not dropped,
        // slot is valid
        unsafe { init.__init(slot).map_err(AllocOrInitError::Init)? };
        // SAFETY: all fields have been initialized
        Ok(unsafe { this.assume_init() })
    }
}

#[cfg(any(feature = "alloc", feature = "std"))]
impl<T> InPlaceInit<T> for Arc<T> {
    type Error<E> = AllocOrInitError<E>;

    fn pin_init<E>(init: impl PinInit<T, E>) -> Result<Pin<Self>, Self::Error<E>> {
        let mut this = Arc::try_new_uninit()?;
        // SAFETY: `this` has refcount = 1
        let slot = unsafe { Arc::get_mut_unchecked(&mut this).as_mut_ptr() };
        // SAFETY: when init errors/panics, slot will get deallocated but not dropped,
        // slot is valid and will not be moved because of the `Pin::new_unchecked`
        unsafe { init.__pinned_init(slot).map_err(AllocOrInitError::Init)? };
        // SAFETY: all fields have been initialized
        Ok(unsafe { Pin::new_unchecked(this.assume_init()) })
    }

    fn init<E>(init: impl Init<T, E>) -> Result<Self, Self::Error<E>> {
        let mut this = Arc::try_new_uninit()?;
        // SAFETY: `this` has refcount = 1
        let slot = unsafe { Arc::get_mut_unchecked(&mut this).as_mut_ptr() };
        // SAFETY: when init errors/panics, slot will get deallocated but not dropped,
        // slot is valid
        unsafe { init.__init(slot).map_err(AllocOrInitError::Init)? };
        // SAFETY: all fields have been initialized
        Ok(unsafe { this.assume_init() })
    }
}

#[cfg(any(feature = "alloc", feature = "std"))]
impl<T> InPlaceInit<T> for Rc<T> {
    type Error<E> = AllocOrInitError<E>;

    fn pin_init<E>(init: impl PinInit<T, E>) -> Result<Pin<Self>, Self::Error<E>> {
        let mut this = Rc::try_new_uninit()?;
        // SAFETY: `this` has refcount = 1
        let slot = unsafe { Rc::get_mut_unchecked(&mut this).as_mut_ptr() };
        // SAFETY: when init errors/panics, slot will get deallocated but not dropped,
        // slot is valid and will not be moved because of the `Pin::new_unchecked`
        unsafe { init.__pinned_init(slot).map_err(AllocOrInitError::Init)? };
        // SAFETY: all fields have been initialized
        Ok(unsafe { Pin::new_unchecked(this.assume_init()) })
    }

    fn init<E>(init: impl Init<T, E>) -> Result<Self, Self::Error<E>> {
        let mut this = Rc::try_new_uninit()?;
        // SAFETY: `this` has refcount = 1
        let slot = unsafe { Rc::get_mut_unchecked(&mut this).as_mut_ptr() };
        // SAFETY: when init errors/panics, slot will get deallocated but not dropped,
        // slot is valid
        unsafe { init.__init(slot).map_err(AllocOrInitError::Init)? };
        // SAFETY: all fields have been initialized
        Ok(unsafe { this.assume_init() })
    }
}

/// Marker trait for types that can be initialized by writing just zeroes.
///
/// # Safety
///
/// The bit pattern consisting of only zeroes must be a valid bit pattern for the type.
pub unsafe trait Zeroable {}

/// Create a new zeroed T.
///
/// The returned initializer will write `0x00` to every byte of the given slot.
pub fn zeroed<T: Zeroable + Unpin>() -> impl Init<T> {
    // SAFETY: because `T: Zeroable`, all bytes zero is a valid bit pattern for `T`
    //         and because we write all zeroes, the memory is initialized.
    unsafe {
        init_from_closure(|slot: *mut T| {
            slot.write_bytes(0, 1);
            Ok(())
        })
    }
}

/// An initializer that leaves the memory uninitialized.
///
/// The initializer is a no-op. The slot memory is not changed.
pub fn uninit<T>() -> impl Init<MaybeUninit<T>> {
    // SAFETY: The memory is allowed to be uninitialized.
    unsafe { init_from_closure(|_| Ok(())) }
}

/// Convert a value into an initializer.
///
/// Directly moves the value into the given slot.
pub fn from_value<T>(value: T) -> impl Init<T> {
    // SAFETY: we use the value to initialize the slot.
    unsafe {
        init_from_closure(move |slot: *mut T| {
            slot.write(value);
            Ok(())
        })
    }
}

macro_rules! impl_zeroable {
    ($($t:ty),*) => {
        $(unsafe impl Zeroable for $t {})*
    };
}
// All primitives that are allowed to be zero.
impl_zeroable!(
    bool, char, u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64
);
// There is nothing to zero.
impl_zeroable!(core::marker::PhantomPinned, Infallible, ());

// We are allowed to zero padding bytes.
unsafe impl<const N: usize, T: Zeroable> Zeroable for [T; N] {}

// There is nothing to zero.
unsafe impl<T: ?Sized> Zeroable for PhantomData<T> {}

// `null` pointer is valid.
unsafe impl<T: ?Sized> Zeroable for *mut T {}
unsafe impl<T: ?Sized> Zeroable for *const T {}

macro_rules! impl_tuple_zeroable {
    ($(,)?) => {};
    ($first:ident, $($t:ident),* $(,)?) => {
        // all elements are zeroable and padding can be zero
        unsafe impl<$first: Zeroable, $($t: Zeroable),*> Zeroable for ($first, $($t),*) {}
        impl_tuple_zeroable!($($t),* ,);
    }
}

impl_tuple_zeroable!(A, B, C, D, E, F, G, H, I, J);