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
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
//! Crate to check if a variable got correctly [dropped]. This crate is mostly useful in unit
//! tests for code involving [`ManuallyDrop`], [`MaybeUninit`], unsafe memory management,
//! custom containers, and more.
//!
//! [dropped]: https://doc.rust-lang.org/reference/destructors.html
//! [`ManuallyDrop`]: std::mem::ManuallyDrop
//! [`MaybeUninit`]: std::mem::MaybeUninit
//!
//! # Concepts
//!
//! The main struct of this crate is [`DropTracker`]. Once you initialize a tracker, you call
//! [`DropTracker::track`] on it to get a [`DropItem`]. Each drop item is identified by a key;
//! the key can be used at any time to check the state of the item and see if it's alive or if
//! it has been dropped.
//!
//! # Examples
//!
//! This is how you would test that a container like [`Vec`] drops all its items when the container
//! is dropped:
//!
//! ```
//! use drop_tracker::DropTracker;
//!
//! let mut tracker = DropTracker::new();
//!
//! // Create a new vector and add a bunch of elements to it. The elements in this case are
//! // identified by integer keys (1, 2, 3), but any hashable type would work.
//! let v = vec![tracker.track(1),
//!              tracker.track(2),
//!              tracker.track(3)];
//!
//! // Assert that all elements in the vector are alive
//! tracker.all_alive(1..=3)
//!        .expect("expected all elements to be alive");
//!
//! // Once the vector is dropped, all items should be dropped with it
//! drop(v);
//! tracker.all_dropped(1..=3)
//!        .expect("expected all elements to be dropped");
//! ```
//!
//! This is how you would test a struct that involves [`MaybeUninit`]:
//!
//! ```should_panic
//! # #![allow(dead_code)]
//! use std::mem::MaybeUninit;
//!
//! struct MyOption<T> {
//!     set: bool,
//!     data: MaybeUninit<T>,
//! }
//!
//! impl<T> MyOption<T> {
//!     fn none() -> Self {
//!         Self { set: false, data: MaybeUninit::uninit() }
//!     }
//!
//!     fn some(x: T) -> Self {
//!         Self { set: true, data: MaybeUninit::new(x) }
//!     }
//! }
//!
//! // BUG: MyOption<T> does not implement Drop!
//! // BUG: The instance inside `data` may be initialized but not be properly destructed!
//!
//! // BUG: The following code will silently leak memory:
//! let opt = MyOption::some(String::from("hello"));
//! drop(opt); // the String does not get deallocated
//!
//! // DropTracker is able to catch this sort of bugs:
//! use drop_tracker::DropTracker;
//!
//! let mut tracker = DropTracker::new();
//! let opt = MyOption::some(tracker.track("item"));
//!
//! tracker.state(&"item")
//!        .alive()
//!        .expect("item is expected to be alive"); // works
//!
//! drop(opt);
//!
//! tracker.state(&"item")
//!        .dropped()
//!        .expect("item is expected to be dropped"); // panics, meaning that the bug was detected
//! ```
//!
//! # Double drop
//!
//! [`DropItem`] will panic if it gets dropped twice or more, as this is generally a bug and may
//! cause undefined behavior. This feature can be used to identify bugs with code using
//! [`ManuallyDrop`](std::mem::ManuallyDrop), [`MaybeUninit`](std::mem::MaybeUninit) or
//! [`std::ptr::drop_in_place`], like in the following example:
//!
//! ```should_panic
//! use std::ptr;
//! use drop_tracker::DropTracker;
//!
//! let mut tracker = DropTracker::new();
//! let mut item = tracker.track("something");
//!
//! unsafe { ptr::drop_in_place(&mut item); } // ok
//! unsafe { ptr::drop_in_place(&mut item); } // panic!
//! ```
//!
//! # Use in collections
//!
//! The [`DropItem`] instances returned by [`DropTracker::track`] hold a clone of the key passed
//! to `track`. The `DropItem`s are [comparable](std::cmp) and [hashable](std::hash) if the
//! underlying key is. This makes `DropItem` instances usable directly in collections like
//! [`HashMap`](std::collections::HashMap), [`BTreeMap`](std::collections::BTreeMap),
//! [`HashSet`](std::collections::HashSet) and many more.
//!
//! Here is an example involving [`HashSet`](std::collections::HashSet):
//!
//! ```
//! use drop_tracker::DropTracker;
//! use std::collections::HashSet;
//!
//! let mut tracker = DropTracker::new();
//!
//! let mut set = HashSet::from([
//!     tracker.track(1),
//!     tracker.track(2),
//!     tracker.track(3),
//! ]);
//!
//! set.remove(&3);
//!
//! tracker.state(&1).alive().expect("first item should be alive");
//! tracker.state(&2).alive().expect("second item should be alive");
//! tracker.state(&3).dropped().expect("third item should be dropped");
//! ```
//!
//! Keys are required to be hashable and unique. If you need [`DropItem`] to hold a non-hashable
//! value, or a repeated value, you can construct a [`DropItem`] with an arbitrary value using
//! [`DropTracker::track_with_value`]:
//!
//! ```
//! use drop_tracker::DropTracker;
//!
//! let mut tracker = DropTracker::new();
//!
//! // Construct items identified by integers and holding floats (which are not hashable)
//! let item1 = tracker.track_with_value(1, 7.52);
//! let item2 = tracker.track_with_value(2, 3.89);
//!
//! // Items compare according to their value
//! assert!(item1 > item2); // 7.52 > 3.89
//!
//! // Items that support comparison can be put in a vector and sorted
//! let mut v = vec![item1, item2];
//! v.sort_by(|x, y| x.partial_cmp(y).unwrap());
//! ```

#![warn(missing_debug_implementations)]
#![warn(missing_docs)]
#![warn(pointer_structural_match)]
#![warn(unreachable_pub)]
#![warn(unused_crate_dependencies)]
#![warn(unused_qualifications)]

#![doc(test(attr(deny(warnings))))]

#[cfg(test)]
mod tests;

mod itemtraits;

use std::borrow::Borrow;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::error::Error;
use std::fmt;
use std::hash::Hash;
use std::iter::FusedIterator;
use std::mem::MaybeUninit;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;

/// A type that represents the state of a [`DropItem`]: either alive or dropped.
///
/// See the [module documentation](self) for details.
#[must_use = "you should check whether the status is alive or dropped"]
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum State {
    /// The item is alive.
    Alive,
    /// The item has been dropped, and its destructor has been called.
    Dropped,
}

impl State {
    /// Returns `true` if the state is [`Alive`](State::Alive).
    ///
    /// # Examples
    ///
    /// ```
    /// use drop_tracker::State;
    ///
    /// assert!(State::Alive.is_alive());
    /// assert!(!State::Dropped.is_alive());
    /// ```
    #[inline]
    #[must_use = "if you intended to assert that this is alive, consider `.alive().expect()`"]
    pub const fn is_alive(&self) -> bool {
        match self {
            Self::Alive => true,
            Self::Dropped => false,
        }
    }

    /// Returns `true` if the state is [`Dropped`](State::Dropped).
    ///
    /// # Examples
    ///
    /// ```
    /// use drop_tracker::State;
    ///
    /// assert!(State::Dropped.is_dropped());
    /// assert!(!State::Alive.is_dropped());
    /// ```
    #[inline]
    #[must_use = "if you intended to assert that this is dropped, consider `.dropped().expect()`"]
    pub const fn is_dropped(&self) -> bool {
        match self {
            Self::Alive => false,
            Self::Dropped => true,
        }
    }

    /// Returns [`Ok`] if the state is [`Alive`](State::Alive), [`Err`] otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use drop_tracker::DroppedError;
    /// use drop_tracker::State;
    ///
    /// assert_eq!(State::Alive.alive(), Ok(()));
    /// assert_eq!(State::Dropped.alive(), Err(DroppedError));
    /// ```
    #[inline]
    #[must_use = "if you intended to assert that this is alive, consider `.alive().expect()`"]
    pub const fn alive(&self) -> Result<(), DroppedError> {
        match self {
            Self::Alive => Ok(()),
            Self::Dropped => Err(DroppedError),
        }
    }

    /// Returns [`Ok`] if the state is [`Dropped`](State::Dropped), [`Err`] otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use drop_tracker::AliveError;
    /// use drop_tracker::State;
    ///
    /// assert_eq!(State::Dropped.dropped(), Ok(()));
    /// assert_eq!(State::Alive.dropped(), Err(AliveError));
    /// ```
    #[inline]
    #[must_use = "if you intended to assert that this is dropped, consider `.dropped().expect()`"]
    pub const fn dropped(&self) -> Result<(), AliveError> {
        match self {
            Self::Alive => Err(AliveError),
            Self::Dropped => Ok(()),
        }
    }
}

// Uses an `AtomicBool` (as opposed to e.g. a `RefCell`) to ensure that `DropTracker` and
// `DropItem` are `Send`, `Sync` and `UnwindSafe`.
#[derive(Clone, Debug)]
struct StateCell(Arc<AtomicBool>);

impl StateCell {
    #[inline]
    #[must_use]
    fn new(state: State) -> Self {
        Self(Arc::new(AtomicBool::new(state.is_dropped())))
    }

    #[inline]
    fn get(&self) -> State {
        match self.0.load(Ordering::Relaxed) {
            false => State::Alive,
            true  => State::Dropped,
        }
    }

    #[inline]
    fn replace(&mut self, state: State) -> State {
        match self.0.swap(state.is_dropped(), Ordering::Relaxed) {
            false => State::Alive,
            true  => State::Dropped,
        }
    }

    #[inline]
    #[must_use]
    fn is_alive(&self) -> bool {
        self.get().is_alive()
    }

    #[inline]
    #[must_use]
    fn is_dropped(&self) -> bool {
        self.get().is_dropped()
    }
}

/// Creates [`DropItem`]s and tracks their state.
///
/// [`DropItem`]s can be created using [`track`](DropTracker::track) or
/// [`try_track`](DropTracker::try_track) and their state can be later checked using
/// [`state`](DropTracker::state).
///
/// [`DropItem`]s are identified by keys. A key can be of any type that implement the [`Hash`]
/// and [`Eq`] traits, which include, for example: [`u32`], [`char`], [`str`], ...
///
/// See the [module documentation](self) for details.
#[derive(Default, Debug)]
pub struct DropTracker<K> {
    tracked: HashMap<K, StateCell>,
}

impl<K> DropTracker<K> {
    /// Creates a new empty `DropTracker`.
    ///
    /// # Examples
    ///
    /// ```
    /// use drop_tracker::DropTracker;
    ///
    /// let tracker = DropTracker::<u32>::new();
    /// assert_eq!(tracker.tracked().count(), 0);
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            tracked: HashMap::new(),
        }
    }

    /// Returns an iterator over the keys tracked by this `DropTracker`.
    ///
    /// The order of keys returned by this iterator is non deterministic.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![allow(unused_variables)]
    /// use drop_tracker::DropTracker;
    ///
    /// let mut tracker = DropTracker::new();
    /// let item_a = tracker.track("a");
    /// let item_b = tracker.track("b");
    /// let item_c = tracker.track("c");
    ///
    /// let mut keys = tracker.tracked()
    ///                       .collect::<Vec<&&str>>();
    /// keys.sort();
    /// assert_eq!(keys, [&"a", &"b", &"c"]);
    /// ```
    pub fn tracked(&self) -> impl Clone + Iterator<Item = &K> + ExactSizeIterator + FusedIterator {
        self.tracked.keys()
    }

    /// Returns an iterator over the keys tracked by this `DropTracker` that are alive.
    ///
    /// The order of keys returned by this iterator is non deterministic.
    ///
    /// # Examples
    ///
    /// ```
    /// use drop_tracker::DropTracker;
    ///
    /// let mut tracker = DropTracker::new();
    /// let item_a = tracker.track("a");
    /// let item_b = tracker.track("b");
    /// let item_c = tracker.track("c");
    ///
    /// drop(item_c);
    ///
    /// let mut alive_keys = tracker.alive()
    ///                             .collect::<Vec<&&str>>();
    /// alive_keys.sort();
    /// assert_eq!(alive_keys, [&"a", &"b"]);
    ///
    /// drop(item_a);
    /// drop(item_b);
    ///
    /// assert_eq!(tracker.alive().count(), 0);
    /// ```
    pub fn alive(&self) -> impl Clone + Iterator<Item = &K> + FusedIterator {
        self.tracked.iter()
                    .filter(|(_, state)| state.is_alive())
                    .map(|(key, _)| key)
    }

    /// Returns an iterator over the keys tracked by this `DropTracker` that have been dropped.
    ///
    /// The order of keys returned by this iterator is non deterministic.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![allow(unused_variables)]
    /// use drop_tracker::DropTracker;
    ///
    /// let mut tracker = DropTracker::new();
    /// let item_a = tracker.track("a");
    /// let item_b = tracker.track("b");
    /// let item_c = tracker.track("c");
    ///
    /// assert_eq!(tracker.dropped().count(), 0);
    ///
    /// drop(item_a);
    /// drop(item_b);
    ///
    /// let mut alive_keys = tracker.dropped()
    ///                             .collect::<Vec<&&str>>();
    /// alive_keys.sort();
    /// assert_eq!(alive_keys, [&"a", &"b"]);
    /// ```
    pub fn dropped(&self) -> impl Clone + Iterator<Item = &K> + FusedIterator {
        self.tracked.iter()
                    .filter(|(_, state)| state.is_dropped())
                    .map(|(key, _)| key)
    }

    /// Forgets all the items tracked by this `DropTracker`.
    ///
    /// The `DropItem`s previously returned by the tracker will still work normally, but it will no
    /// longer be possible to query their status after forgetting them.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![allow(unused_variables)]
    /// use drop_tracker::DropTracker;
    ///
    /// let mut tracker = DropTracker::new();
    /// assert_eq!(tracker.tracked().count(), 0);
    ///
    /// let item_a = tracker.track("a");
    /// let item_b = tracker.track("b");
    /// let item_c = tracker.track("c");
    /// assert_eq!(tracker.tracked().count(), 3);
    ///
    /// tracker.forget_all();
    /// assert_eq!(tracker.tracked().count(), 0);
    /// ```
    pub fn forget_all(&mut self) {
        self.tracked.clear();
    }

    /// Forgets all the items tracked by this `DropTracker` that have been dropped.
    ///
    /// The `DropItem`s previously returned by the tracker will still work normally, but it will no
    /// longer be possible to query their status after forgetting them.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![allow(unused_variables)]
    /// use drop_tracker::DropTracker;
    ///
    /// let mut tracker = DropTracker::new();
    /// assert_eq!(tracker.tracked().count(), 0);
    ///
    /// let item_a = tracker.track("a");
    /// let item_b = tracker.track("b");
    /// let item_c = tracker.track("c");
    /// assert_eq!(tracker.tracked().count(), 3);
    ///
    /// // After dropping an item, the item is still tracked
    /// drop(item_a);
    /// drop(item_b);
    /// assert_eq!(tracker.tracked().count(), 3);
    ///
    /// // Use `forget_dropped` to lose track of items that have been dropped
    /// tracker.forget_dropped();
    /// assert_eq!(tracker.tracked().count(), 1);
    ///
    /// let mut keys = tracker.tracked()
    ///                       .collect::<Vec<&&str>>();
    /// keys.sort();
    /// assert_eq!(keys, [&"c"]);
    /// ```
    pub fn forget_dropped(&mut self) {
        self.tracked.retain(|_, state| state.is_alive())
    }
}

impl<K: Hash + Eq> DropTracker<K> {
    /// Creates a new [`DropItem`] identified by the given key.
    ///
    /// The value held by the `DropItem` is a clone of the key. Use
    /// [`DropTracker::track_with_value`] if you wish to specify a custom value.
    ///
    /// # Panics
    ///
    /// Panics if the key is already used by another tracked item.
    ///
    /// Call [`forget`](DropTracker::forget),
    /// [`forget_dropped`](DropTracker::forget_dropped) or
    /// [`forget_all`](DropTracker::forget_all) if you wish to reuse a key from an item you no
    /// longer need to track.
    ///
    /// See [`try_track`](DropTracker::try_track) for a variant of this method that does not panic.
    ///
    /// # Examples
    ///
    /// ```
    /// use drop_tracker::DropTracker;
    /// use drop_tracker::State;
    ///
    /// let mut tracker = DropTracker::new();
    ///
    /// let item = tracker.track("abc");
    /// assert_eq!(tracker.state("abc"), State::Alive);
    ///
    /// drop(item);
    /// assert_eq!(tracker.state("abc"), State::Dropped);
    /// ```
    ///
    /// Using the same key twice causes a panic:
    ///
    /// ```should_panic
    /// # #![allow(unused_variables)]
    /// use drop_tracker::DropTracker;
    ///
    /// let mut tracker = DropTracker::new();
    ///
    /// let item1 = tracker.track("abc");
    /// let item2 = tracker.track("abc"); // panics!
    /// ```
    ///
    /// Use [`forget`](DropTracker::forget) to reuse the same key:
    ///
    /// ```
    /// # #![allow(unused_variables)]
    /// use drop_tracker::DropTracker;
    ///
    /// let mut tracker = DropTracker::new();
    ///
    /// let item1 = tracker.track("abc");
    /// let _ = tracker.forget("abc");
    /// let item2 = tracker.track("abc"); // works
    /// ```
    pub fn track(&mut self, key: K) -> DropItem<K>
        where K: Clone
    {
        self.try_track(key).expect("cannot track key")
    }

    /// Creates a new [`DropItem`] identified by the given key, or [`Err`] if the key is
    /// already in use.
    ///
    /// The value held by the `DropItem` is a clone of the key. Use
    /// [`DropTracker::try_track_with_value`] if you wish to specify a custom value.
    ///
    /// See also [`track`](DropTracker::track).
    ///
    /// # Examples
    ///
    /// ```
    /// # #![allow(unused_variables)]
    /// use drop_tracker::DropTracker;
    ///
    /// let mut tracker = DropTracker::new();
    ///
    /// let item = tracker.try_track("abc");
    /// assert!(item.is_ok());
    ///
    /// let item = tracker.try_track("abc");
    /// assert!(item.is_err()); // key is already used
    /// ```
    pub fn try_track(&mut self, key: K) -> Result<DropItem<K>, CollisionError>
        where K: Clone
    {
        let value = key.clone();
        self.try_track_with_value(key, value)
    }

    /// Creates a new [`DropItem`] identified by the given key and holding the given value.
    ///
    /// # Panics
    ///
    /// Panics if the key is already used by another tracked item.
    ///
    /// Call [`forget`](DropTracker::forget),
    /// [`forget_dropped`](DropTracker::forget_dropped) or
    /// [`forget_all`](DropTracker::forget_all) if you wish to reuse a key from an item you no
    /// longer need to track.
    ///
    /// See [`try_track_with_value`](DropTracker::try_track_with_value) for a variant of this
    /// method that does not panic.
    ///
    /// # Examples
    ///
    /// ```
    /// use drop_tracker::DropTracker;
    /// use drop_tracker::State;
    ///
    /// let mut tracker = DropTracker::new();
    ///
    /// let item = tracker.track_with_value("abc", vec![1, 2, 3]);
    /// assert_eq!(tracker.state("abc"), State::Alive);
    ///
    /// drop(item);
    /// assert_eq!(tracker.state("abc"), State::Dropped);
    /// ```
    ///
    /// Using the same key twice causes a panic:
    ///
    /// ```should_panic
    /// # #![allow(unused_variables)]
    /// use drop_tracker::DropTracker;
    ///
    /// let mut tracker = DropTracker::new();
    ///
    /// let item1 = tracker.track_with_value("abc", vec![1, 2, 3]);
    /// let item2 = tracker.track_with_value("abc", vec![4, 5, 6]); // panics!
    /// ```
    ///
    /// Use [`forget`](DropTracker::forget) to reuse the same key:
    ///
    /// ```
    /// # #![allow(unused_variables)]
    /// use drop_tracker::DropTracker;
    ///
    /// let mut tracker = DropTracker::new();
    ///
    /// let item1 = tracker.track_with_value("abc", vec![1, 2, 3]);
    /// let _ = tracker.forget("abc");
    /// let item2 = tracker.track_with_value("abc", vec![4, 5, 6]); // works
    /// ```
    pub fn track_with_value<V>(&mut self, key: K, value: V) -> DropItem<V> {
        self.try_track_with_value(key, value).expect("cannot track key")
    }

    /// Creates a new [`DropItem`] identified by the given key and holding the given value, or
    /// [`Err`] if the key is already in use.
    ///
    /// See also [`track_with_value`](DropTracker::track_with_value).
    ///
    /// # Examples
    ///
    /// ```
    /// # #![allow(unused_variables)]
    /// use drop_tracker::DropTracker;
    ///
    /// let mut tracker = DropTracker::new();
    ///
    /// let item = tracker.try_track_with_value("abc", vec![1, 2, 3]);
    /// assert!(item.is_ok());
    ///
    /// let item = tracker.try_track_with_value("abc", vec![4, 5, 6]);
    /// assert!(item.is_err()); // key is already used
    /// ```
    pub fn try_track_with_value<V>(&mut self, key: K, value: V) -> Result<DropItem<V>, CollisionError> {
        let state = StateCell::new(State::Alive);
        match self.tracked.entry(key) {
            Entry::Occupied(_) => Err(CollisionError),
            Entry::Vacant(entry) => {
                entry.insert(state.clone());
                Ok(DropItem::new(value, state))
            },
        }
    }
}

impl<K: Hash + Eq> DropTracker<K> {
    /// Checks the state of a [`DropItem`] tracked by this `DropTracker`: [alive](State::Alive) or
    /// [dropped](State::Dropped).
    ///
    /// # Panics
    ///
    /// Panics if the given key is not tracked.
    ///
    /// See [`try_state`](DropTracker::try_state) for a variant of this method that does not panic.
    ///
    /// # Examples
    ///
    /// ```
    /// use drop_tracker::DropTracker;
    /// use drop_tracker::State;
    ///
    /// let mut tracker = DropTracker::new();
    ///
    /// let item = tracker.track("abc");
    /// assert_eq!(tracker.state("abc"), State::Alive);
    ///
    /// drop(item);
    /// assert_eq!(tracker.state("abc"), State::Dropped);
    /// ```
    ///
    /// Querying a key that is not tracked causes a panic:
    ///
    /// ```should_panic
    /// # #![allow(unused_variables)]
    /// use drop_tracker::DropTracker;
    ///
    /// let mut tracker = DropTracker::new();
    ///
    /// let item = tracker.track("abc");
    /// let state = tracker.state("def"); // panics!
    /// ```
    pub fn state<Q>(&self, key: &Q) -> State
        where K: Borrow<Q>,
              Q: Hash + Eq + ?Sized
    {
        self.try_state(key).expect("cannot get state")
    }

    /// Checks the state of a [`DropItem`] tracked by this `DropTracker`: [alive](State::Alive) or
    /// [dropped](State::Dropped). Returns [`Err`] it the given key is not tracked.
    ///
    /// See also [`state`](DropTracker::state).
    ///
    /// # Examples
    ///
    /// ```
    /// use drop_tracker::DropTracker;
    /// use drop_tracker::NotTrackedError;
    /// use drop_tracker::State;
    ///
    /// let mut tracker = DropTracker::new();
    ///
    /// let item = tracker.track("abc");
    /// assert_eq!(tracker.try_state("abc"), Ok(State::Alive));
    /// assert_eq!(tracker.try_state("def"), Err(NotTrackedError));
    ///
    /// drop(item);
    /// assert_eq!(tracker.try_state("abc"), Ok(State::Dropped));
    /// assert_eq!(tracker.try_state("def"), Err(NotTrackedError));
    /// ```
    pub fn try_state<Q>(&self, key: &Q) -> Result<State, NotTrackedError>
        where K: Borrow<Q>,
              Q: Hash + Eq + ?Sized
    {
        self.tracked.get(key)
                    .ok_or(NotTrackedError)
                    .map(|state| state.get())
    }

    /// Forgets an item tracked by this `DropTracker`, and returns its current state
    /// ([alive](State::Alive) or [dropped](State::Dropped)).
    ///
    /// The `DropItem`s previously returned by the tracker will still work normally, but it will no
    /// longer be possible to query their status after forgetting them.
    ///
    /// # Panics
    ///
    /// Panics if the given key is not tracked.
    ///
    /// See [`try_forget`](DropTracker::try_forget) for a variant of this method that does not panic.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![allow(unused_variables)]
    /// use drop_tracker::DropTracker;
    /// use drop_tracker::State;
    ///
    /// let mut tracker = DropTracker::new();
    ///
    /// let item = tracker.track("a");
    /// assert!(tracker.is_tracked("a"));
    ///
    /// assert_eq!(tracker.forget("a"), State::Alive);
    /// assert!(!tracker.is_tracked("a"));
    /// ```
    ///
    /// Forgetting a key that is not tracked causes a panic:
    ///
    /// ```should_panic
    /// # #![allow(unused_variables)]
    /// use drop_tracker::DropTracker;
    ///
    /// let mut tracker = DropTracker::new();
    ///
    /// let item = tracker.track("abc");
    /// let state = tracker.forget("def"); // panics!
    /// ```
    pub fn forget<Q>(&mut self, key: &Q) -> State
        where K: Borrow<Q>,
              Q: Hash + Eq + ?Sized
    {
        self.try_forget(key).expect("cannot forget item")
    }

    /// Forgets an item tracked by this `DropTracker`, and returns its current state
    /// ([alive](State::Alive) or [dropped](State::Dropped)), or [`Err`] if the item is not
    /// tracked.
    ///
    /// The `DropItem`s previously returned by the tracker will still work normally, but it will no
    /// longer be possible to query their status after forgetting them.
    ///
    /// See also [`forget`](DropTracker::forget).
    ///
    /// # Examples
    ///
    /// ```
    /// # #![allow(unused_variables)]
    /// use drop_tracker::DropTracker;
    /// use drop_tracker::NotTrackedError;
    /// use drop_tracker::State;
    ///
    /// let mut tracker = DropTracker::new();
    ///
    /// let item = tracker.track("a");
    /// assert!(tracker.is_tracked("a"));
    ///
    /// assert_eq!(tracker.try_forget("a"), Ok(State::Alive));
    /// assert_eq!(tracker.try_forget("b"), Err(NotTrackedError));
    /// ```
    pub fn try_forget<Q>(&mut self, key: &Q) -> Result<State, NotTrackedError>
        where K: Borrow<Q>,
              Q: Hash + Eq + ?Sized
    {
        self.tracked.remove(key)
                    .ok_or(NotTrackedError)
                    .map(|state| state.get())
    }

    /// Returns [`true`] if an item identified by the given key is tracked by this `DropTracker`,
    /// [`false`] otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![allow(unused_variables)]
    /// use drop_tracker::DropTracker;
    ///
    /// let mut tracker = DropTracker::new();
    /// assert!(!tracker.is_tracked("abc"));
    ///
    /// let item = tracker.track("abc");
    /// assert!(tracker.is_tracked("abc"));
    /// ```
    #[must_use]
    pub fn is_tracked<Q>(&self, key: &Q) -> bool
        where K: Borrow<Q>,
              Q: Hash + Eq + ?Sized
    {
        self.try_state(key).is_ok()
    }

    /// Returns [`Ok`] if all the given keys point to items that are [alive](State::Alive),
    /// [`Err`] otherwise.
    ///
    /// An error may be returned in two cases: either a key is not tracked, or it has been dropped.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![allow(unused_variables)]
    /// use drop_tracker::DropTracker;
    /// use drop_tracker::NotAllAliveError;
    ///
    /// let mut tracker = DropTracker::new();
    ///
    /// let item1 = tracker.track(1);
    /// let item2 = tracker.track(2);
    /// let item3 = tracker.track(3);
    /// let item4 = tracker.track(4);
    ///
    /// drop(item3);
    /// drop(item4);
    ///
    /// assert_eq!(tracker.all_alive([1, 2]), Ok(()));
    ///
    /// assert_eq!(tracker.all_alive([1, 2, 3, 4, 5, 6]),
    ///            Err(NotAllAliveError {
    ///                dropped: vec![3, 4],
    ///                untracked: vec![5, 6],
    ///            }));
    /// ```
    pub fn all_alive<Q, Item, Iter>(&self, iter: Iter) -> Result<(), NotAllAliveError<Item>>
        where K: Borrow<Q>,
              Q: Hash + Eq + ?Sized,
              Item: Borrow<Q>,
              Iter: IntoIterator<Item = Item>
    {
        // Vec won't allocate any memory until items are pushed to it, so if this method does not
        // fail, no memory will be allocated
        let mut err = NotAllAliveError {
            dropped: Vec::new(),
            untracked: Vec::new(),
        };

        for key in iter {
            match self.try_state(key.borrow()) {
                Ok(State::Alive) => (),
                Ok(State::Dropped) => err.dropped.push(key),
                Err(NotTrackedError) => err.untracked.push(key),
            }
        }

        if err.dropped.is_empty() && err.untracked.is_empty() {
            Ok(())
        } else {
            Err(err)
        }
    }

    /// Returns [`Ok`] if all the given keys point to items that are [dropped](State::Dropped),
    /// [`Err`] otherwise.
    ///
    /// An error may be returned in two cases: either a key is not tracked, or it has been dropped.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![allow(unused_variables)]
    /// use drop_tracker::DropTracker;
    /// use drop_tracker::NotAllDroppedError;
    ///
    /// let mut tracker = DropTracker::new();
    ///
    /// let item1 = tracker.track(1);
    /// let item2 = tracker.track(2);
    /// let item3 = tracker.track(3);
    /// let item4 = tracker.track(4);
    ///
    /// drop(item3);
    /// drop(item4);
    ///
    /// assert_eq!(tracker.all_dropped([3, 4]), Ok(()));
    ///
    /// assert_eq!(tracker.all_dropped([1, 2, 3, 4, 5, 6]),
    ///            Err(NotAllDroppedError {
    ///                alive: vec![1, 2],
    ///                untracked: vec![5, 6],
    ///            }));
    /// ```
    pub fn all_dropped<Q, Item, Iter>(&self, iter: Iter) -> Result<(), NotAllDroppedError<Item>>
        where K: Borrow<Q>,
              Q: Hash + Eq + ?Sized,
              Item: Borrow<Q>,
              Iter: IntoIterator<Item = Item>
    {
        // Vec won't allocate any memory until items are pushed to it, so if this method does not
        // fail, no memory will be allocated
        let mut err = NotAllDroppedError {
            alive: Vec::new(),
            untracked: Vec::new(),
        };

        for key in iter {
            match self.try_state(key.borrow()) {
                Ok(State::Alive) => err.alive.push(key),
                Ok(State::Dropped) => (),
                Err(NotTrackedError) => err.untracked.push(key),
            }
        }

        if err.alive.is_empty() && err.untracked.is_empty() {
            Ok(())
        } else {
            Err(err)
        }
    }
}

/// An item that will notify the parent [`DropTracker`] once it gets dropped.
///
/// `DropItem` instances are created by [`DropTracker::track`], [`DropTracker::track_with_value`],
/// and related functions. `DropItem` instances may contain an "underlying value" that affects the
/// item behavior when used with standard traits. The underlying value is either:
///
/// * a clone of `key` when constructing an item using `track(key)` (implicit); or
/// * `value` when constructing an item using `track_with_value(key, value)` (explicit).
///
/// To check whether an item is alive or has been dropped, use [`DropTracker::state`] or see the
/// documentation for [`DropTracker`] for alternatives.
///
/// # Coercing and borrowing
///
/// `DropItem` instances may be [_coerced_](std::ops::Deref) and [_borrowed_](std::borrow::Borrow)
/// as the the underlying value type. This means that, for example, if you create a `DropItem`
/// using `track(String::from("abc"))`, you may call all of the `String` methods on that item.
///
/// `DropItem` also implements the standard traits [`PartialEq`](std::cmp::PartialEq),
/// [`Eq`](std::cmp::Eq), [`PartialOrd`](std::cmp::PartialOrd), [`Ord`](std::cmp::Ord) and
/// [`Hash`](std::hash::Hash), [`Display`](std::fmt::Display), [`Debug`](std::fmt::Debug) if the
/// type of the underlying value implements them.
///
/// # Cloning
///
/// `DropItem` does not implement the [`Clone`] trait as it would introduce ambiguity with respect
/// to understanding whether the item has been dropped or is still alive when using
/// [`DropTracker::state`].
///
/// # Double drop
///
/// `DropItem` instances can be dropped twice or more. Doing so will cause a panic, but will not
/// cause undefined behavior (unless you're calling drop on an invalid memory location). The panic
/// on double drop is an useful feature to detect logic errors in destructors.
///
/// # Safety
///
/// Borrowing or performing operations on the underlying value of a `DropItem` is generally safe
/// when using safe Rust code. However, `DropItem`s are often used in unsafe code and are used to
/// detect potential bugs. In those circumstances, it is possible to trigger undefined behavior.
/// In particular, borrowing or performing operations on a `DropItem` while another thread is
/// dropping will result in undefined behavior (although it must be noted that this is a bug in the
/// caller code and is not something that should happen in safe Rust code).
///
/// Only [`Drop`](std::ops::Drop) on a `DropItem` is guaranteed to be safe in all circumstances.
///
/// # Examples
///
/// ```
/// use drop_tracker::DropTracker;
///
/// let mut tracker = DropTracker::<u32>::new();
///
/// // Create an item using `123u32` as the key. Implicitly, this also sets its value to `123u32`
/// let item = tracker.track(123);
///
/// // Check that the item is alive
/// tracker.state(&123).alive().expect("item should be alive");
///
/// // Dereference the value of the item
/// assert_eq!(*item, 123);
/// assert!(!item.is_power_of_two());
///
/// // Drop the item and check that it really got dropped
/// drop(item);
/// tracker.state(&123).dropped().expect("item should be dropped");
///
/// // Create a new item, this time using an explicit `String` value
/// let abc_item = tracker.track_with_value(111, String::from("abc"));
///
/// // Comparison with other items using `String` work using the underlying `String`
/// // operations
/// assert_eq!(abc_item, tracker.track_with_value(222, String::from("abc")));
/// assert_ne!(abc_item, tracker.track_with_value(333, String::from("def")));
/// assert!(abc_item < tracker.track_with_value(444, String::from("def")));
///
/// // Display, debug and hashing also work using the underlying `String` operations
/// assert_eq!(format!("{}", abc_item), "abc");
/// assert_eq!(format!("{:?}", abc_item), "DropItem { value: \"abc\", state: Alive }");
///
/// use std::collections::hash_map::DefaultHasher;
/// use std::hash::Hash;
/// use std::hash::Hasher;
/// fn hash<T: Hash + ?Sized>(x: &T) -> u64 {
///     let mut hasher = DefaultHasher::new();
///     x.hash(&mut hasher);
///     hasher.finish()
/// }
/// assert_eq!(hash(&abc_item), hash(&"abc"));
///
/// // Methods on `String` can be called transparently on items
/// assert_eq!(abc_item.to_ascii_uppercase(), "ABC");
/// ```
///
/// Using hashable items in a set, with an implicit underlying value:
///
/// ```
/// use drop_tracker::DropTracker;
/// use std::collections::HashSet;
///
/// let mut tracker = DropTracker::new();
///
/// let mut set = HashSet::from([
///     tracker.track(1),
///     tracker.track(2),
///     tracker.track(3),
/// ]);
///
/// set.remove(&3);
///
/// tracker.state(&1).alive().expect("first item should be alive");
/// tracker.state(&2).alive().expect("second item should be alive");
/// tracker.state(&3).dropped().expect("third item should be dropped");
/// ```
///
/// Using hashable items in a set, with an explicit underlying value:
///
/// ```
/// use drop_tracker::DropTracker;
/// use std::collections::HashSet;
///
/// let mut tracker = DropTracker::new();
///
/// let mut set = HashSet::from([
///     tracker.track_with_value(1, String::from("first")),
///     tracker.track_with_value(2, String::from("second")),
///     tracker.track_with_value(3, String::from("third")),
/// ]);
///
/// set.remove("third");
///
/// tracker.state(&1).alive().expect("first item should be alive");
/// tracker.state(&2).alive().expect("second item should be alive");
/// tracker.state(&3).dropped().expect("third item should be dropped");
/// ```
#[must_use = "if you don't use this item, it will get automatically dropped"]
pub struct DropItem<V> {
    value: MaybeUninit<V>,
    state: Option<StateCell>,
}

impl<V> DropItem<V> {
    const fn new(value: V, state: StateCell) -> Self {
        Self {
            value: MaybeUninit::new(value),
            state: Some(state),
        }
    }
}

impl<V> Drop for DropItem<V> {
    fn drop(&mut self) {
        // The use of an Option might seem redundant, but it's actually needed to safely detect and
        // report double drops. Without the Option, we would be touching shared memory behind an Rc
        // that probably does not exist anymore, causing memory corruption. The Option makes this a
        // bit safer (assuming that the DropItem memory has not been moved or altered), and also
        // prevents a double drop on the Rc.
        match self.state.take() {
            Some(mut state) => {
                if state.replace(State::Dropped).is_dropped() {
                    panic!("item dropped twice");
                }
                // SAFETY: `state` was `Some(State::Alive)`, which means that `value` has not been
                // dropped yet and that `value` is initialized.
                unsafe { self.value.assume_init_drop() };
            },
            None => {
                panic!("item dropped twice");
            },
        }
    }
}

/// Error signaling that an item was expected to have been dropped, but it's [alive](State::Alive).
///
/// See [`State::dropped`] for more information and examples.
#[derive(PartialEq, Eq, Debug)]
pub struct AliveError;

impl fmt::Display for AliveError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt("item is alive", f)
    }
}

impl Error for AliveError {
}

/// Error signaling that an item was expected to be alive, but it was [dropped](State::Dropped).
///
/// See [`State::alive`] for more information and examples.
#[derive(PartialEq, Eq, Debug)]
pub struct DroppedError;

impl fmt::Display for DroppedError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt("item is dropped", f)
    }
}

impl Error for DroppedError {
}

/// Error returned when trying to place multiple items with the same key inside the same [`DropTracker`].
///
/// See [`DropTracker::try_track`] for more information and examples.
#[derive(PartialEq, Eq, Debug)]
pub struct CollisionError;

impl fmt::Display for CollisionError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt("another item with the same key is already tracked", f)
    }
}

impl Error for CollisionError {
}

/// Error returned when failing to query the status of an item with a key that is not known to [`DropTracker`].
///
/// See [`DropTracker::try_state`] for more information and examples.
#[derive(PartialEq, Eq, Debug)]
pub struct NotTrackedError;

impl fmt::Display for NotTrackedError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt("item is not tracked", f)
    }
}

impl Error for NotTrackedError {
}

/// Error returned when failing to assert that a set of items is all [alive](State::Alive).
///
/// See [`DropTracker::all_alive`] for more information and examples.
#[derive(PartialEq, Eq, Debug)]
pub struct NotAllAliveError<K> {
    /// Sequence of keys that were expected to be alive, but were dropped.
    pub dropped: Vec<K>,
    /// Sequence of keys that were expected to be alive, but are not tracked by the
    /// [`DropTracker`].
    pub untracked: Vec<K>,
}

impl<K: fmt::Debug> fmt::Display for NotAllAliveError<K> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "not all items are alive: ")?;
        if !self.dropped.is_empty() {
            write!(f, "dropped: {:?}", &self.dropped)?;
        }
        if !self.untracked.is_empty() {
            if !self.dropped.is_empty() {
                write!(f, ", ")?;
            }
            write!(f, "not tracked: {:?}", &self.untracked)?;
        }
        Ok(())
    }
}

impl<K: fmt::Debug> Error for NotAllAliveError<K> {
}

/// Error returned when failing to assert that a set of items is all [dropped](State::Dropped).
///
/// See [`DropTracker::all_dropped`] for more information and examples.
#[derive(PartialEq, Eq, Debug)]
pub struct NotAllDroppedError<K> {
    /// Sequence of keys that were expected to be dropped, but are alive.
    pub alive: Vec<K>,
    /// Sequence of keys that were expected to be dropped, but are not tracked by the
    /// [`DropTracker`].
    pub untracked: Vec<K>,
}

impl<K: fmt::Debug> fmt::Display for NotAllDroppedError<K> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "not all items are dropped: ")?;
        if !self.alive.is_empty() {
            write!(f, "alive: {:?}", &self.alive)?;
        }
        if !self.untracked.is_empty() {
            if !self.alive.is_empty() {
                write!(f, ", ")?;
            }
            write!(f, "not tracked: {:?}", &self.untracked)?;
        }
        Ok(())
    }
}

impl<K: fmt::Debug> Error for NotAllDroppedError<K> {
}