partial_this 0.5.1

Type-safe partial construction
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
//! Type-safe partial construction.
//!
//! The [`partial`] attribute macro lets you build a struct field-by-field,
//! while the type system guarantees that each field is initialized at most once
//! and that `done()` is only callable once every field has
//! been set.
//!
//! # Example
//!
//! ```rust
//! use partial_this::partial;
//!
//! #[partial]
//! pub struct Foo {
//!     pub foo: i32,
//!     pub bar: f32,
//! }
//!
//! fn main() {
//!     let foo = Foo::partial(Box::new_uninit())
//!         .with_foo(1)
//!         .with_bar(1.0)
//!         .done();
//!
//!     assert_eq!(foo.foo, 1);
//!     assert_eq!(foo.bar, 1.0);
//! }
//! ```
//!
//! # Multiple partial sources
//!
//! The initial storage can be a `Box`, `Rc`, `Arc`, an owned `MaybeUninit`, or a mutable
//! reference, producing `Box<T>`, `Rc<T>`, `Arc<T>`, `T`, or `&mut T` respectively:
//!
//! ```rust
//! use partial_this::partial;
//! use core::mem::MaybeUninit;
//!
//! #[partial]
//! pub struct Foo {
//!     pub foo: i32,
//!     pub bar: f32,
//! }
//!
//! fn main() {
//!     // From Box<MaybeUninit<T>>
//!     let a: Box<Foo> = Foo::partial(Box::new_uninit())
//!         .with_foo(1)
//!         .with_bar(2.0)
//!         .done();
//!
//!     // From MaybeUninit<T>
//!     let b: Foo = Foo::partial(MaybeUninit::uninit())
//!         .with_foo(1)
//!         .with_bar(2.0)
//!         .done();
//!
//!     // From &mut MaybeUninit<T>
//!     let mut buf = MaybeUninit::uninit();
//!     let c: &mut Foo = Foo::partial(&mut buf)
//!         .with_foo(1)
//!         .with_bar(2.0).done();
//! #
//! #   let _ = (a, b, c);
//! }
//! ```
//!
//! # Field initialization
//!
//! Each field's builder method can be called in **any order**, but **at most
//! once**:
//!
//! ```rust
//! # use partial_this::partial;
//! #
//! #[partial]
//! pub struct Foo {
//!     pub foo: i32,
//!     pub bar: f32,
//! }
//! # fn main() {
//!
//! let p = Foo::partial(Box::new_uninit());
//!
//! let p = p.with_bar(1.0);
//! let p = p.with_foo(1);
//!
//! let foo = p.done();
//! assert_eq!(foo.foo, 1);
//! assert_eq!(foo.bar, 1.0);
//! # }
//! ```
//!
//! A second call is rejected at compile time:
//!
//! ```compile_fail
//! # use partial_this::partial;
//! #
//! # #[partial]
//! # pub struct Foo {
//! #     pub foo: i32,
//! #     pub bar: f32,
//! # }
//! #
//! # fn main() {
//! # let p = Foo::partial(Box::new_uninit());
//! let p = p.with_foo(123);
//! let p = p.with_foo(456);
//! // Error: method cannot be called on `...` due to unsatisfied trait bounds
//! # }
//! ```
//! ### Emplace
//! Some fields are awkward to build from a ready-made value. Use
//! `emplace_field` to initialize one in place — it hands your closure a
//! `&mut MaybeUninit<T>` to write into.  
//! This is especially useful when a field
//! is itself a `#[partial]` struct: build it directly inside the parent's
//! storage, so no intermediate allocation is needed:
//!
//! ```rust
//! # use partial_this::partial;
//! # use core::mem::MaybeUninit;
//! #
//! #[partial]
//! pub struct Point {
//!     pub x: i32,
//!     pub y: i32,
//! }
//!
//! #[partial]
//! pub struct Line {
//!     pub start: Point,
//!     pub end: Point,
//! }
//!
//! # fn main() {
//! // Place `Point` values directly inside `Line`'s storage.
//! let line = Line::partial(Box::new_uninit())
//!     .emplace_start(|slot: &mut MaybeUninit<Point>| {
//!         // placement new
//!         Point::partial(slot).with_x(1).with_y(2).done()
//!     })
//!     // or just write
//!     .emplace_end(|slot| slot.write(Point { x: 3, y: 4 }))
//!     .done();
//!
//! assert_eq!((line.start.x, line.start.y), (1, 2));
//! assert_eq!((line.end.x, line.end.y), (3, 4));
//! # }
//! ```
//!
//! > **Note:** You can write a placement-new constructor to simplify usage, but
//! > that is outside the scope of this crate.
//! > ```rust
//! > # use partial_this::{partial, AnyUninit};
//! > # use core::mem::MaybeUninit;
//! > #
//! > # #[partial]
//! > # pub struct Point {
//! > #     pub x: i32,
//! > #     pub y: i32,
//! > # }
//! > #
//! > impl Point {
//! >     pub fn new_in<U>(place: U, x: i32, y: i32) -> U::Inited
//! >     where
//! >         U: AnyUninit<Target = Self>,
//! >     {
//! >         // perhaps some complex calculations
//! >         Self::partial(place).with_x(x).with_y(y).done()
//! >     }
//! > }
//! > # 
//! > # #[partial]
//! > # pub struct Line {
//! > #     pub start: Point,
//! > #     pub end: Point,
//! > # }
//! > 
//! > # fn main() {
//! > let line = Line::partial(Box::new_uninit())
//! >     .emplace_start(|slot| Point::new_in(slot, 1, 2))
//! >     .emplace_end(|slot| Point::new_in(slot, 3, 4))
//! >     .done();
//! > #
//! > # assert_eq!((line.start.x, line.start.y), (1, 2));
//! > # assert_eq!((line.end.x, line.end.y), (3, 4));
//! > # }
//! > ```
//!
//! # Field access
//!
//! After a field is initialized you can read it or mutate it:
//!
//! ```rust
//! # use partial_this::partial;
//! #
//! #[partial]
//! pub struct Foo {
//!     pub foo: i32,
//!     pub bar: f32,
//! }
//!
//! # fn main() {
//! let mut p = Foo::partial(Box::new_uninit())
//!     .with_foo(1);
//!
//! assert_eq!(*p.get_foo(), 1);
//!
//! p.set_foo(123);
//!
//! let foo = p.with_bar(2.0)
//!     .done();
//!
//! assert_eq!(foo.foo, 123);
//! # }
//! ```
//!
//! # Tuple and generic structs
//!
//! Tuple structs use `0`, `1`, ... as field method names
//!
//! ```rust
//! # use partial_this::partial;
//! #
//! #[partial]
//! pub struct Bar(i32, f32);
//!
//! # fn main() {
//! let bar = Bar::partial(Box::new_uninit())
//!     .with_0(1)
//!     .with_1(2.0)
//!     .done();
//!
//! assert_eq!(bar.0, 1);
//! assert_eq!(bar.1, 2.0);
//! # }
//! ```
//! Generic and lifetime-parameterized structs are also supported:
//! ```rust
//! # use partial_this::partial;
//! #
//! #[partial]
//! pub struct Pair<'a, T> {
//!     pub name: &'a str,
//!     pub value: T,
//! }
//!
//! # fn main() {
//! let pair = Pair::<String>::partial(Box::new_uninit())
//!     .with_name("x")
//!     .with_value(String::from("y"))
//!     .done();
//!
//! assert_eq!(pair.name, "x");
//! assert_eq!(pair.value, "y");
//! # }
//! ```
//!
//! # Others
//!
//! - **Multiple partial sources**: `Box::new_uninit()`, `MaybeUninit::uninit()`
//!   or `&mut MaybeUninit` all work as the initial storage.
//! - **Field initialization methods**: each field offers `with_field(value)`,
//!   `emplace_field(init)`, and `uninit_field()`; the builder methods can be
//!   called in any order, and at most once (a second call is a compile time error).
//! - **Field access methods**: after a field is initialized you can read it with
//!   `get_field()`, mutate it with `get_mut_field()`, or assign with
//!   `set_field(value)`.
//! - **`done()`**: finalizes the builder once every field is initialized, both
//!   as an inherent method and through the [`CtorComplete`] trait.
//! - **Drop safety**: partially-built values drop already-initialized fields in
//!   reverse order of initialization (the last field set is dropped first).
//! - **Field visibility**: the builder type `PartialStructName` is re-exported for a
//!   struct `StructName`, and field methods are available directly on the builder.
//!
//! # Safety
//!
//! The unsafe code in this crate is self-contained: it writes initialized fields
//! into a [`MaybeUninit`] buffer and only assumes the target value is initialized
//! after every field has been written.

#![cfg_attr(not(test), no_std)]

extern crate alloc;
extern crate self as partial_this;

use alloc::{boxed::Box, rc::Rc, sync::Arc};
use core::mem::MaybeUninit;

pub use typenum;

/// Generates a type-safe partial construction for a struct.
///
/// Applying the attribute to a struct emits a module that contains one marker
/// struct per field, alongside an inherent `partial` constructor on the struct
/// and a `Partial<N>` builder type (re-exported as `PartialFoo`).
///
/// # Example
///
/// ```
/// use partial_this::partial;
///
/// #[partial]
/// #[derive(Debug)]
/// pub struct Foo {
///     pub a: i32,
///     pub b: f32,
/// }
///
/// fn main() {
///     let foo = Foo::partial(Box::new_uninit())
///         .with_a(1)
///         .with_b(2.0)
///         .done();
///     assert_eq!(foo.a, 1);
///     assert_eq!(foo.b, 2.0);
/// }
/// ```
///
/// # Multiple partial sources
///
/// `Box::new_uninit()`, `MaybeUninit::uninit()`, and `&mut MaybeUninit` are all
/// accepted as the initial storage, finalizing to `Box<T>`, `T`, or `&mut T`:
///
/// ```
/// use partial_this::partial;
/// use core::mem::MaybeUninit;
///
/// #[partial]
/// pub struct Foo {
///     pub a: i32,
///     pub b: f32,
/// }
///
/// fn main() {
///     let boxed: Box<Foo> = Foo::partial(Box::new_uninit()).with_a(1).with_b(2.0).done();
///     let owned: Foo = Foo::partial(MaybeUninit::uninit()).with_a(1).with_b(2.0).done();
///
///     let mut buf = MaybeUninit::uninit();
///     let borrowed: &mut Foo = Foo::partial(&mut buf).with_a(1).with_b(2.0).done();
///     let _ = (boxed, owned, borrowed);
/// }
/// ```
///
/// # Field initialization & access
///
/// Field builders can be called in any order, but at most once; after a field is
/// initialized you can read or mutate it:
///
/// ```
/// use partial_this::partial;
///
/// #[partial]
/// pub struct Foo {
///     pub a: i32,
///     pub b: f32,
/// }
///
/// fn main() {
///     let mut p = Foo::partial(Box::new_uninit());
///     let p = p.with_a(1);
///     assert_eq!(*p.get_a(), 1);
///     let mut p = p;
///     p.set_a(123);
///     let p = p.with_b(2.0);
///     let foo = p.done();
///     assert_eq!(foo.a, 123);
/// }
/// ```
///
/// # Tuple and generic structs
///
/// Tuple structs use `with_0`, `with_1`, ... as field method names; generic and
/// lifetime structs are supported too:
///
/// ```
/// use partial_this::partial;
///
/// #[partial]
/// pub struct Bar(i32, f32);
///
/// #[partial]
/// pub struct Pair<'a, T> {
///     pub name: &'a str,
///     pub value: T,
/// }
///
/// fn main() {
///     let bar = Bar::partial(Box::new_uninit()).with_0(1).with_1(2.0).done();
///     assert_eq!(bar.0, 1);
///
///     let pair = Pair::<String>::partial(Box::new_uninit())
///         .with_name("x")
///         .with_value(String::from("y"))
///         .done();
///     assert_eq!(pair.name, "x");
///     assert_eq!(pair.value, "y");
/// }
/// ```
///
/// # Behavior
///
/// - **Field initialization** — each field offers `with_field(value)`,
///   `emplace_field(init)`, and `uninit_field()`; the builder methods can be
///   called in any order, but at most once (a second call is a compile error).
/// - **Field access** — after a field is initialized you can read it with
///   `get_field()`, mutate it with `get_mut_field()`, or assign with
///   `set_field(value)`.
/// - **`done()`** — finalizes the builder once every field is initialized, both
///   as an inherent method and through the [`CtorComplete`] trait.
/// - **Drop safety** — dropping an unfinished builder drops already-initialized
///   fields in reverse order of initialization (the last field set is dropped
///   first).
/// - **Field visibility** — the builder type `PartialStructName` is re-exported
///   for a struct `StructName`; field methods are available directly on it.
///
/// # Config
///
/// - `module = name` — name of the generated module. Defaults to a snake_case
///   variant of the struct name, e.g. `foo_partial` for `Foo`.
/// - `crate_name = name` — crate that exposes `ThisPtr`/`AnyUninit`/`typenum`.
///   Defaults to `partial_this`; set it to the dependency alias when the crate
///   is renamed in `Cargo.toml`.
/// - `pub_use = true|false` — whether to re-export the generated `PartialXxx`
///   builder type with `pub use`. Defaults to `true`; set to `false` to keep it
///   module-local. Even when `true`, if the struct or any field is not `pub`
///   (which would leak a private type into a public interface), the re-export
///   falls back to a module-local `use`.
pub use partial_this_macro::partial;

pub use uninit_this::*;
mod uninit_this {
    use super::*;

    /// A source of uninitialized storage for a value of type
    /// [`Target`](Self::Target).
    ///
    /// Implemented for `MaybeUninit<T>`, `&mut MaybeUninit<T>`,
    /// `Box<MaybeUninit<T>>`, `Rc<MaybeUninit<T>>` and `Arc<MaybeUninit<T>>`.
    /// Implementations expose the underlying [`MaybeUninit`](core::mem::MaybeUninit)
    /// and allow assuming the storage has been initialized.
    pub trait AnyUninit {
        /// The type to be constructed.
        type Target;

        /// The type produced once [`assume_init`](Self::assume_init) is called.
        type Inited;

        /// Borrows the underlying uninitialized storage.
        ///
        /// # Safety
        ///
        /// The storage must not have been initialized yet.
        unsafe fn get(&self) -> &MaybeUninit<Self::Target>;

        /// Mutably borrows the underlying uninitialized storage.
        ///
        /// # Safety
        ///
        /// The storage must not have been initialized yet.
        unsafe fn get_mut(&mut self) -> &mut MaybeUninit<Self::Target>;

        /// Assumes the storage has been initialized and returns the value.
        ///
        /// # Safety
        ///
        /// Every field must have been initialized before the value is assumed.
        unsafe fn assume_init(self) -> Self::Inited;
    }

    impl<'a, T> AnyUninit for &'a mut MaybeUninit<T> {
        type Target = T;

        type Inited = &'a mut T;

        #[cfg_attr(not(debug_assertions), inline(always))]
        unsafe fn assume_init(self) -> Self::Inited {
            unsafe { self.assume_init_mut() }
        }

        #[cfg_attr(not(debug_assertions), inline(always))]
        unsafe fn get(&self) -> &MaybeUninit<Self::Target> {
            self
        }

        #[cfg_attr(not(debug_assertions), inline(always))]
        unsafe fn get_mut(&mut self) -> &mut MaybeUninit<Self::Target> {
            self
        }
    }
    impl<T> AnyUninit for MaybeUninit<T> {
        type Target = T;
        type Inited = T;

        #[cfg_attr(not(debug_assertions), inline(always))]
        unsafe fn assume_init(self) -> Self::Inited {
            unsafe { self.assume_init() }
        }

        #[cfg_attr(not(debug_assertions), inline(always))]
        unsafe fn get(&self) -> &MaybeUninit<Self::Target> {
            self
        }

        #[cfg_attr(not(debug_assertions), inline(always))]
        unsafe fn get_mut(&mut self) -> &mut MaybeUninit<Self::Target> {
            self
        }
    }
    impl<T> AnyUninit for Box<MaybeUninit<T>> {
        type Target = T;
        type Inited = Box<T>;

        #[cfg_attr(not(debug_assertions), inline(always))]
        unsafe fn assume_init(self) -> Self::Inited {
            unsafe { self.assume_init() }
        }

        #[cfg_attr(not(debug_assertions), inline(always))]
        unsafe fn get(&self) -> &MaybeUninit<Self::Target> {
            self
        }

        #[cfg_attr(not(debug_assertions), inline(always))]
        unsafe fn get_mut(&mut self) -> &mut MaybeUninit<Self::Target> {
            self
        }
    }
    impl<T> AnyUninit for Rc<MaybeUninit<T>> {
        type Target = T;
        type Inited = Rc<T>;

        #[cfg_attr(not(debug_assertions), inline(always))]
        unsafe fn assume_init(self) -> Self::Inited {
            unsafe { self.assume_init() }
        }

        #[cfg_attr(not(debug_assertions), inline(always))]
        unsafe fn get(&self) -> &MaybeUninit<Self::Target> {
            self
        }

        #[cfg_attr(not(debug_assertions), inline(always))]
        unsafe fn get_mut(&mut self) -> &mut MaybeUninit<Self::Target> {
            Rc::get_mut(self).unwrap()
        }
    }
    impl<T> AnyUninit for Arc<MaybeUninit<T>> {
        type Target = T;
        type Inited = Arc<T>;

        #[cfg_attr(not(debug_assertions), inline(always))]
        unsafe fn assume_init(self) -> Self::Inited {
            unsafe { self.assume_init() }
        }

        #[cfg_attr(not(debug_assertions), inline(always))]
        unsafe fn get(&self) -> &MaybeUninit<Self::Target> {
            self
        }

        #[cfg_attr(not(debug_assertions), inline(always))]
        unsafe fn get_mut(&mut self) -> &mut MaybeUninit<Self::Target> {
            Arc::get_mut(self).unwrap()
        }
    }
}

/// Provides access to the underlying uninitialized storage of a builder node.
#[doc(hidden)]
pub trait ThisPtr {
    /// The struct type being constructed.
    type Target;

    /// Borrows the underlying `MaybeUninit` storage.
    fn this(&self) -> &MaybeUninit<Self::Target>;

    /// Mutably borrows the underlying `MaybeUninit` storage.
    fn this_mut(&mut self) -> &mut MaybeUninit<Self::Target>;
}

impl<U: AnyUninit> ThisPtr for U {
    type Target = U::Target;

    #[cfg_attr(not(debug_assertions), inline(always))]
    fn this(&self) -> &MaybeUninit<Self::Target> {
        unsafe { U::get(self) }
    }

    #[cfg_attr(not(debug_assertions), inline(always))]
    fn this_mut(&mut self) -> &mut MaybeUninit<Self::Target> {
        unsafe { U::get_mut(self) }
    }
}

/// Finalizes a partially-constructed value once every field is initialized.
///
/// The code generated by [`partial`] implements this trait, exposing `done()`
/// through a public interface. `T` is the finalized type produced by
/// [`AnyUninit::Inited`] — for a struct `Foo` this is `Box<Foo>`, `Foo`, or
/// `&mut Foo` depending on the storage — and not the raw [`AnyUninit::Target`]
/// struct type. `T` is a generic parameter rather than an associated type, so
/// implementing the trait never forces the generated builder's private state to
/// appear in a public trait interface.
pub trait CtorComplete<T> {
    fn done(self) -> T;
}

#[cfg(test)]
#[allow(nonstandard_style)]
pub mod test_reference {
    #[derive(Debug)]
    pub struct Foo {
        pub foo: i32,
        pub bar: f32,
    }

    pub use should_be_generated_by_macro::*;
    mod should_be_generated_by_macro {
        use crate::ThisPtr;

        #[derive(Debug)]
        pub struct foo<N: ThisPtr<Target = super::Foo>>(N);
        #[derive(Debug)]
        pub struct bar<N: ThisPtr<Target = super::Foo>>(N);

        impl<N: ThisPtr<Target = super::Foo>> ThisPtr for foo<N> {
            type Target = super::Foo;

            fn this(&self) -> &core::mem::MaybeUninit<Self::Target> {
                self.0.this()
            }

            fn this_mut(&mut self) -> &mut core::mem::MaybeUninit<Self::Target> {
                self.0.this_mut()
            }
        }

        impl<N: ThisPtr<Target = super::Foo>> ThisPtr for bar<N> {
            type Target = super::Foo;

            fn this(&self) -> &core::mem::MaybeUninit<Self::Target> {
                self.0.this()
            }

            fn this_mut(&mut self) -> &mut core::mem::MaybeUninit<Self::Target> {
                self.0.this_mut()
            }
        }

        impl<N: ThisPtr<Target = super::Foo>> Drop for foo<N> {
            fn drop(&mut self) {
                unsafe { core::ptr::drop_in_place(&mut (*self.0.this_mut().as_mut_ptr()).foo) };
            }
        }

        impl<N: ThisPtr<Target = super::Foo>> Drop for bar<N> {
            fn drop(&mut self) {
                unsafe { core::ptr::drop_in_place(&mut (*self.0.this_mut().as_mut_ptr()).bar) };
            }
        }

        pub use private::Partial as PartialFoo;

        mod private {
            #![allow(clippy::missing_safety_doc)]
            use super::*;
            use crate::{AnyUninit, ThisPtr};
            use core::mem::{ManuallyDrop, MaybeUninit};
            use core::ops::{BitAnd, BitOr};
            use typenum::{Or, Shleft, U0, U1, U2, U3};

            #[derive(Debug)]
            pub struct Partial<N>(N);

            impl super::super::Foo {
                pub fn partial<U>(this: U) -> private::Partial<U>
                where
                    U: crate::AnyUninit<Target = super::super::Foo>,
                {
                    private::Partial(this)
                }
            }

            pub trait State: ThisPtr<Target = super::super::Foo> {
                type Flags;
                type Inited;

                unsafe fn assume_init(self) -> Self::Inited;
            }

            impl<U: AnyUninit<Target = super::super::Foo>> State for U {
                type Flags = U0;

                type Inited = U::Inited;

                unsafe fn assume_init(self) -> Self::Inited {
                    unsafe { U::assume_init(self) }
                }
            }

            impl<N> State for foo<N>
            where
                N: State,
                N::Flags: BitOr<U1>,
            {
                type Flags = Or<N::Flags, U1>;
                type Inited = N::Inited;

                unsafe fn assume_init(self) -> Self::Inited {
                    unsafe {
                        let this = ManuallyDrop::new(self);
                        core::ptr::read(&this.0).assume_init()
                    }
                }
            }

            impl<N> State for bar<N>
            where
                N: State,
                N::Flags: BitOr<Shleft<U1, U1>>,
            {
                type Flags = Or<N::Flags, U2>;
                type Inited = N::Inited;

                unsafe fn assume_init(self) -> Self::Inited {
                    unsafe {
                        let this = ManuallyDrop::new(self);
                        core::ptr::read(&this.0).assume_init()
                    }
                }
            }

            impl<N> Partial<N>
            where
                N: ThisPtr<Target = super::super::Foo> + State,
                N::Flags: BitAnd<U1, Output = U0>,
            {
                pub fn uninit_foo(&mut self) -> &mut MaybeUninit<i32> {
                    unsafe {
                        let ptr: *mut _ = &mut (*self.0.this_mut().as_mut_ptr()).foo;
                        &mut *ptr.cast()
                    }
                }

                pub unsafe fn assume_init_foo(self) -> Partial<foo<N>> {
                    Partial(foo(self.0))
                }

                pub fn with_foo(mut self, value: i32) -> Partial<foo<N>> {
                    unsafe { core::ptr::write(&mut (*self.0.this_mut().as_mut_ptr()).foo, value) };
                    Partial(foo(self.0))
                }

                pub fn emplace_foo(
                    mut self,
                    init: impl for<'a> FnOnce(&'a mut MaybeUninit<i32>) -> &'a mut i32,
                ) -> Partial<foo<N>> {
                    _ = init(self.uninit_foo());
                    Partial(foo(self.0))
                }
            }

            impl<N> Partial<N>
            where
                N: ThisPtr<Target = super::super::Foo> + State,
                N::Flags: BitAnd<U2, Output = U0>,
            {
                pub fn uninit_bar(&mut self) -> &mut MaybeUninit<f32> {
                    unsafe {
                        let ptr: *mut _ = &mut (*self.0.this_mut().as_mut_ptr()).bar;
                        &mut *ptr.cast()
                    }
                }

                pub unsafe fn assume_init_bar(self) -> Partial<bar<N>> {
                    Partial(bar(self.0))
                }

                pub fn with_bar(mut self, value: f32) -> Partial<bar<N>> {
                    unsafe { core::ptr::write(&mut (*self.0.this_mut().as_mut_ptr()).bar, value) };
                    Partial(bar(self.0))
                }

                pub fn emplace_bar(
                    mut self,
                    init: impl for<'a> FnOnce(&'a mut MaybeUninit<f32>) -> &'a mut f32,
                ) -> Partial<bar<N>> {
                    _ = init(self.uninit_bar());
                    Partial(bar(self.0))
                }
            }

            impl<N> Partial<N>
            where
                N: ThisPtr<Target = super::super::Foo> + State,
                N::Flags: BitAnd<U1, Output = U1>,
            {
                pub fn set_foo(&mut self, value: i32) -> &mut Self {
                    *self.get_mut_foo() = value;
                    self
                }
                pub fn get_foo(&self) -> &i32 {
                    unsafe { &(*self.0.this().as_ptr()).foo }
                }
                pub fn get_mut_foo(&mut self) -> &mut i32 {
                    unsafe { &mut (*self.0.this_mut().as_mut_ptr()).foo }
                }
            }

            impl<N> Partial<N>
            where
                N: ThisPtr<Target = super::super::Foo> + State,
                N::Flags: BitAnd<U2, Output = U2>,
            {
                pub fn set_bar(&mut self, value: f32) -> &mut Self {
                    *self.get_mut_bar() = value;
                    self
                }
                pub fn get_bar(&self) -> &f32 {
                    unsafe { &(*self.0.this().as_ptr()).bar }
                }
                pub fn get_mut_bar(&mut self) -> &mut f32 {
                    unsafe { &mut (*self.0.this_mut().as_mut_ptr()).bar }
                }
            }

            impl<N> Partial<N>
            where
                N: State<Flags = U3>,
            {
                pub fn done(self) -> N::Inited {
                    unsafe { self.0.assume_init() }
                }
            }

            impl<N> crate::CtorComplete<N::Inited> for Partial<N>
            where
                N: State<Flags = U3>,
            {
                fn done(self) -> N::Inited {
                    self.done()
                }
            }
        }
    }

    #[test]
    fn test1() {
        let a = Foo::partial(Box::new_uninit());
        let mut a = a.with_foo(1);
        a.set_foo(123);
        let a = a.with_bar(456.0).done();
        assert_eq!(a.foo, 123);
        assert_eq!(a.bar, 456.0)
    }
}

#[cfg(test)]
pub mod test_macro {
    use super::*;

    #[partial]
    pub struct Foo {
        pub foo: i32,
        pub bar: f32,
    }

    #[test]
    fn macro_generates_partial() {
        let a = Foo::partial(Box::new_uninit());
        let mut a = a.with_foo(1);
        a.set_foo(123);
        let a = a.with_bar(456.0).done();
        assert_eq!(a.foo, 123);
        assert_eq!(a.bar, 456.0);
    }
}