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
//! [SafeManuallyDrop]: `SafeManuallyDrop`
//! [`SafeManuallyDrop`]: `SafeManuallyDrop`
//! [`SafeManuallyDrop::into_inner_defusing_impl_Drop()`]: `SafeManuallyDrop::into_inner_defusing_impl_Drop()`
//! [`DropManually`]: `DropManually`
//! [`DropManually::drop_manually()`]: `DropManually::drop_manually()`
//! [`appendix`]: `appendix`
//!
//! [`ManuallyDrop`]: `ManuallyDrop`
//! [`::core::ops::Deref`]: `::core::ops::Deref`
//! [`::core::ops::DerefMut`]: `::core::ops::DerefMut`
//! [`Drop`]: `Drop`
//! [`Option`]: `Option`
//! [`From::from()`]: `From::from()`
use ;
/// The crate's prelude.
pub
/// The main/whole point of this whole crate and design: to expose _owned_ access to a `FieldTy`
/// when drop glue is being run.
///
/// - A [`SafeManuallyDrop<FieldTy, ContainingType>`],
/// - with a (mandatory)
/// <code>impl [DropManually\<FieldTy\>][`DropManually`] for ContainingType {</code>,
/// - once it gets dropped / during its drop glue (_e.g._, from within a `ContainingType`),
/// - shall be running the [`DropManually::drop_manually()`] logic on that _owned_ `FieldTy`.
///
/// In practice, this becomes _the_ handy, 0-runtime-overhead, non-`unsafe`, tool to get owned
/// access to a `struct`'s field (or group thereof) during drop glue.
///
/// Indeed, the recipe then becomes:
///
/// 1. Use, instead of a `field: FieldTy`, a wrapped
/// <code>field: [SafeManuallyDrop]\<FieldTy, ContainingType\></code>,
///
/// - (Usually `Self` can be used instead of having to spell out, _verbatim_, the
/// `ContainingType`.)
///
/// - (This wrapper type offers transparent
/// <code>[Deref][`::core::ops::Deref`]{,[Mut][`::core::ops::DerefMut`]}</code>, as well as
/// [`From::from()`] and ["`.into()`"][`SafeManuallyDrop::into_inner_defusing_impl_Drop()`]
/// conversions.)
///
/// 1. then, provide the companion, mandatory,
/// <code>impl [DropManually\<FieldTy\>][`DropManually`] for ContainingType {</code>
///
/// 1. Profit™ from the owned access to `FieldTy` inside of [`DropManually::drop_manually()`]'s
/// body.
///
/// ### "`OverrideDropGlue`" rather than `PrependDropGlue`
///
/// Note that this new drop glue logic for `FieldTy`, defined in [`DropManually::drop_manually()`],
/// shall _supersede_ / override its default drop glue.
///
/// ```rust
/// use ::safe_manually_drop::prelude::*;
///
/// pub struct MyType(SafeManuallyDrop<String, Self>);
///
/// impl DropManually<String> for MyType {
/// fn drop_manually(s: String) {
/// // stuff…
/// } // <- unless `s` has been moved out (e.g., though `mem::forget()`),
/// // `s`' own drop glue (e.g., here, that of `String`) gets automagically
/// // invoked, rather similarly to the classic `Drop` trait.
/// // But the huge difference is that this function body had to *allow* it
/// // to happen, by not having *consumed* the owned `s: String` in some other
/// // way.
/// }
///
/// fn example(it: MyType) {
/// drop(it); // invokes the drop glue of `MyType`,
/// // i.e., the `Drop` impl `for SafeManuallyDrop<String, MyType>`
/// // i.e., `<MyType as DropManually<String>>::drop_manually()`.
/// }
/// ```
///
/// For instance: if, inside of [`DropManually::drop_manually()`], the `FieldTy` is
/// [`::core::mem::forget()`]ten, then `FieldTy`'s own drop glue shall never actually run, much like
/// when a [`ManuallyDrop<FieldTy>`] is [`drop()`]-ped/discarded.
///
/// With that being said, precisely because [`DropManually::drop_manually()`] receives an owned
/// instance of `FieldTy`, this behavior is rather "opt-out": that `FieldTy` owned instance runs
/// out of scope when the function completes, so it will almost always get "dropped" / have its own
/// drop glue being invoked.
///
/// The only exceptions are then when other, ownership-consuming, functions, get called on this
/// value.
///
/// Typically:
///
/// - [`::core::mem::forget()`] to skip/bypass all of the drop glue altogether.
/// - note that a direct [`ManuallyDrop<FieldTy>`] would probably be better in this instance;
/// - an `impl FnOnce()` getting called (the `()`-call consumes ownership);
/// - an owned argument `S` is fed to a function, such as `S` in an `impl FnOnce(S)`;
/// - types using owned type-state patterns, most notably `Transaction::{commit,roll_back}()`.
pub
/// [`SafeManuallyDrop<FieldTy>`] is the safe counterpart of [`ManuallyDrop<FieldTy>`], and the
/// zero-runtime-overhead counterpart of [`Option<FieldTy>`].
///
/// ## Example
///
/// - Using [`ManuallyDrop<FieldTy>`] and `unsafe`:
///
/// ```rust
/// #![deny(unsafe_code)] // require visible `#[allow()]`s in subtle functions.
///
/// use ::core::mem::ManuallyDrop;
///
/// pub
/// struct DeferGuard<T, F : FnOnce(T)> {
/// value: ManuallyDrop<T>,
/// on_drop: ManuallyDrop<F>,
/// }
///
/// impl<T, F : FnOnce(T)> Drop for DeferGuard<T, F> {
/// fn drop(&mut self) {
/// #[allow(unsafe_code)] {
/// let value = unsafe { // 😰
/// ManuallyDrop::take(&mut self.value)
/// };
/// let on_drop = unsafe { // 😰
/// ManuallyDrop::take(&mut self.on_drop)
/// };
/// on_drop(value);
/// }
/// }
/// }
///
/// impl<T, F : FnOnce(T)> ::core::ops::Deref for DeferGuard<T, F> {
/// type Target = T;
///
/// fn deref(&self) -> &T {
/// &self.value
/// }
/// }
/// // And `DerefMut`
/// ```
///
/// - Using [`Option<FieldTy>`] and [`.unwrap()`][`Option::unwrap()`]s everywhere…
///
/// ```rust
/// #![forbid(unsafe_code)]
///
/// struct DeferGuardFields<T, F : FnOnce(T)> {
/// value: T,
/// on_drop: F,
/// }
///
/// pub
/// struct DeferGuard<T, F : FnOnce(T)>(
/// Option<DeferGuardFields<T, F>>,
/// );
///
/// impl<T, F : FnOnce(T)> Drop for DeferGuard<T, F> {
/// fn drop(&mut self) {
/// let DeferGuardFields {
/// value,
/// on_drop,
/// } = self.0.take().unwrap(); // 🤢
/// on_drop(value);
/// }
/// }
///
/// impl<T, F : FnOnce(T)> ::core::ops::Deref for DeferGuard<T, F> {
/// type Target = T;
///
/// fn deref(&self) -> &T {
/// &self
/// .0
/// .as_ref()
/// .unwrap() // 🤮
/// .value
/// }
/// }
/// // And `DerefMut`
/// ```
///
/// - Using [`SafeManuallyDrop<FieldTy, …>`][`SafeManuallyDrop`]: no `unsafe`, no `.unwrap()`s!
///
/// ```rust
/// #![forbid(unsafe_code)]
///
/// use ::safe_manually_drop::{DropManually, SafeManuallyDrop};
///
/// struct DeferGuardFields<T, F : FnOnce(T)> {
/// value: T,
/// on_drop: F,
/// }
///
/// pub
/// struct DeferGuard<T, F : FnOnce(T)>(
/// // rather than `Option<DeferGuardFields<T, F>>`,
/// // or `ManuallyDrop<DeferGuardFields<T, F>>`, use:
/// SafeManuallyDrop<DeferGuardFields<T, F>, Self>,
/// );
///
/// impl<T, F : FnOnce(T)>
/// DropManually<DeferGuardFields<T, F>>
/// for
/// DeferGuard<T, F>
/// {
/// fn drop_manually(
/// DeferGuardFields { value, on_drop }: DeferGuardFields<T, F>,
/// )
/// {
/// on_drop(value);
/// }
/// }
///
/// impl<T, F : FnOnce(T)> ::core::ops::Deref for DeferGuard<T, F> {
/// type Target = T;
///
/// fn deref(&self) -> &T {
/// &self.0.value
/// }
/// }
/// // And `DerefMut`
/// ```
///
/// ## Explanation
///
/// It manages to be non-`unsafe`, w.r.t. [`ManuallyDrop<FieldTy>`], by virtue of having a
/// significantly more restricted use case: that of being used as a `struct`[^or_enum]'s field,
/// and merely **exposing _owned_ access to the `FieldTy` on _drop_**.
///
/// [^or_enum]: (or `enum`, but for the remainder of the explanation, I will stick to talking of
/// `struct`s exclusively, since it's simpler.)
///
/// Such owned access, and _drop_ logic, is exposed and defined in the companion
/// [`DropManually<FieldTy>`] trait.
///
/// In such an `impl`, you shall only have access to that `FieldTy`:
///
/// - no access to sibling field types,
///
/// (this can be trivially worked around by bundling all the necessary fields together inside
/// the [`SafeManuallyDrop<_>`]; _c.f._ the example above with the `DeferGuardFields` helper
/// definition;)
///
/// - nor to the encompassing `struct` altogether.
///
/// The latter is kind of problematic, since the desired drop glue logic is probably strongly tied
/// to such encompassing `struct`.
///
/// Hence that second generic type parameter on [`SafeManuallyDrop<FieldTy, ContainingType>`].
///
/// As its name indicates, it is expected to be the containing/encompassing `struct`:
///
/// ```rust
/// use ::safe_manually_drop::SafeManuallyDrop;
///
/// struct Example {
/// // ^
/// // +-----------------------+
/// // |
/// string: SafeManuallyDrop<String, Self>,
/// }
/// #
/// # impl ::safe_manually_drop::DropManually<String> for Example {
/// # fn drop_manually(_: String) {}
/// # }
/// ```
///
/// That way, this containing `struct` can be used as the `Self`/`impl`ementor type for the drop
/// glue:
///
/// ```rust
/// use ::safe_manually_drop::DropManually;
///
/// # struct Example {
/// # // ^
/// # // +-----------------------+
/// # // |
/// # string: ::safe_manually_drop::SafeManuallyDrop<String, Self>,
/// # }
/// #
/// impl DropManually<String> for Example {
/// fn drop_manually(s: String) {
/// // owned access to `s` here!
/// # let random = || true; // determined by faire dice roll.
/// if random() {
/// drop(s);
/// } else {
/// ::core::mem::forget(s);
/// }
/// }
/// }
/// ```
///
/// ## Going further
///
/// In practice, neither the API of this crate, nor that of any non-macro API for that matter, can
/// ever hope to check, impose, nor control that the `ContainingType` used for a
/// [`SafeManuallyDrop<FieldTy, ContainingType>`] do match that of the containing `struct`.
///
/// And, as a matter of fact, there may even be legitimate cases where you may do so on purpose.
///
/// Indeed, this extra type parameter is, at the end of the day, a mere `impl DropManually`
/// "identifier" / discriminant for it to be possible for anybody to write such impls for arbitrary
/// `FieldTy` types, even when the `FieldTy` is a fully unconstrained/blanket `<T>/<F>` generic
/// type, and/or when it stems from an upstream crate, or even when wanting to repeat
/// `SafeManuallyDrop<FieldTy, …>` multiple types within the same `struct`.
///
/// In such a case, you may want distinct drop logic for one field _vs._ another.
///
/// If so, then consider/notice how what that `ContainingType` _actually_ is, is rather a
/// `DropImplIdentifier/DropImplDiscriminant/DropStrategy` mere `PhantomData`-like type parameter.
///
/// Which means that in this context, you will likely want to involve dedicated phantom types for
/// the `ContainingType, FieldIdentifier` pair:
///
/// ```rust
/// use ::safe_manually_drop::prelude::*;
///
/// use some_lib::Transaction;
/// // where `some_lib` has the following API, say:
/// mod some_lib {
/// pub struct Transaction(());
///
/// // Owned `self` receivers for stronger type-level guarantees.
/// impl Transaction {
/// pub fn commit(self) {}
/// pub fn roll_back(self) {}
/// }
/// }
///
/// enum MyType {
/// AutoCommitOnDrop {
/// txn: SafeManuallyDrop<Transaction, CommitOnDropStrategy>,
/// },
///
/// AutoRollBackOnDrop {
/// txn: SafeManuallyDrop<Transaction, RollBackOnDropStrategy>,
/// },
/// }
///
/// enum CommitOnDropStrategy {}
/// impl DropManually<Transaction> for CommitOnDropStrategy {
/// fn drop_manually(txn: Transaction) {
/// txn.commit();
/// }
/// }
///
/// enum RollBackOnDropStrategy {}
/// impl DropManually<Transaction> for RollBackOnDropStrategy {
/// fn drop_manually(txn: Transaction) {
/// txn.roll_back();
/// }
/// }
/// ```
///
/// ### `repr()` guarantee.
///
/// This type is guaranteed to be a mere `#[repr(transparent)]` wrapper around its `FieldTy`.
///
/// ### A silly, but interesting example: DIY-ing our own `ManuallyDrop<T>`
///
/// ```rust
/// use ::safe_manually_drop::prelude::*;
///
/// pub
/// enum ForgetOnDropStrategy {}
///
/// impl<T> DropManually<T> for ForgetOnDropStrategy {
/// fn drop_manually(value: T) {
/// ::core::mem::forget(value);
/// }
/// }
///
/// pub
/// type ManuallyDrop<T> = SafeManuallyDrop<T, ForgetOnDropStrategy>;
/// ```
///
/// - Note: do not do this in actual code, since calling `forget()` temporarily asserts validity
/// of the `value`, which means the resulting type is completey unable to offer
/// [`ManuallyDrop::take()`]-like APIs of any sort, and whatnot.
pub
/// The impl tying everything together.
///
/// The main reason why an <code>impl [DropManually]</code> Just Works™, thanks to the following
/// blanket `impl`:
///
/// <code>impl\<FieldTy\> Drop for SafeManuallyDrop\<FieldTy, …\> where … : DropManually\<FieldTy\> { </code>
/// Some helper for a nicer diagnostic suggestion/nudge in case of a forgotten second type
/// parameter.