rootcause 0.12.1

A flexible, ergonomic, and inspectable error reporting library for Rust
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
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
use alloc::vec::Vec;

use rootcause_internals::handlers::{ContextHandler, FormattingFunction};

use crate::{
    Report, ReportRef, handlers,
    markers::{self, Cloneable, Dynamic, Local, Mutable, SendSync, Uncloneable},
    report_attachments::ReportAttachments,
    report_collection::{ReportCollectionIntoIter, ReportCollectionIter},
};

/// FIXME: Once rust-lang/rust#132922 gets resolved, we can make the `raw` field
/// an unsafe field and remove this module.
mod limit_field_access {
    use alloc::vec::Vec;
    use core::marker::PhantomData;

    use rootcause_internals::RawReport;

    use crate::markers::{Dynamic, SendSync};

    /// A collection of reports.
    ///
    /// You can think of a [`ReportCollection<C, T>`] as a wrapper around a
    /// `Vec<Report<C, markers::Cloneable, T>>`, however, it has a slightly
    /// different API:
    /// - It provides methods such as [`context`](Self::context) and
    ///   [`context_custom`](Self::context_custom) to create new reports with
    ///   the collection as children.
    /// - It has convenience methods to convert between different context and
    ///   thread safety markers such as [`into_dynamic`](Self::into_dynamic) and
    ///   [`into_local`](Self::into_local).
    /// - It is also possible to convert between different context and thread
    ///   safety markers using the [`From`] and [`Into`] traits.
    #[repr(transparent)]
    pub struct ReportCollection<
        Context: ?Sized + 'static = Dynamic,
        ThreadSafety: 'static = SendSync,
    > {
        /// # Safety
        ///
        /// The following safety invariants are guaranteed to be upheld as long
        /// as this struct exists:
        ///
        /// 1. Either the collection must be empty, `C` must either be a type
        ///    bounded by `Sized`, or C must be `Dynamic`.
        /// 2. Either the collection must be empty or `T` must either be
        ///    `SendSync` or `Local`.
        /// 3. If `C` is a `Sized` type: The contexts contained in all of the
        ///    reports in the `Vec` are of type `C`.
        /// 4. All references to these reports or any sub-reports are compatible
        ///    with shared ownership. Specifically there are no references with
        ///    an assumption that the strong_count is `1`.
        /// 5. If `T = SendSync`: All contexts and attachments in all of the
        ///    reports and all sub-reports must be `Send+Sync`.
        /// 6. If the mutable reference to this struct was created through
        ///    `Self::from_raw_mut` on a `&'a mut Vec<RawReport>`, then
        ///    invariant number 5 is upheld for the entire lifetime of the `&'a
        ///    mut Vec<RawReport>`.
        raw: Vec<RawReport>,
        _context: PhantomData<Context>,
        _thread_safety: PhantomData<ThreadSafety>,
    }

    impl<C: ?Sized, T> ReportCollection<C, T> {
        /// Creates a new [`ReportCollection`] from a vector of raw reports
        ///
        /// # Safety
        ///
        /// The caller must ensure:
        ///
        /// 1. Either the collection must be empty, `C` must either be a type
        ///    bounded by `Sized`, or C must be `Dynamic`.
        /// 2. Either the collection must be empty or `T` must either be
        ///    `SendSync` or `Local`.
        /// 3. If `C` is a `Sized` type: The contexts contained in all of the
        ///    reports in the `Vec` are of type `C`.
        /// 4. All references to these reports or any sub-reports are compatible
        ///    with shared ownership. Specifically there are no references with
        ///    an assumption that the strong_count is `1`.
        /// 5. If `T = SendSync`: All contexts and attachments in all of the
        ///    reports and all sub-reports must be `Send+Sync`
        #[must_use]
        pub(crate) unsafe fn from_raw(raw: Vec<RawReport>) -> Self {
            // SAFETY: We must uphold the safety invariants of the raw field:
            // 1. Guaranteed by the caller
            // 2. Guaranteed by the caller
            // 3. Guaranteed by the caller
            // 4. Guaranteed by the caller
            // 5. Guaranteed by the caller
            // 6. Not applicable
            Self {
                raw,
                _context: PhantomData,
                _thread_safety: PhantomData,
            }
        }

        /// Creates a reference to a [`ReportCollection`] from reference to a
        /// vector of raw reports
        ///
        /// # Safety
        ///
        /// The caller must ensure:
        ///
        /// 1. Either the collection must be empty, `C` must either be a type
        ///    bounded by `Sized`, or C must be `Dynamic`.
        /// 2. Either the collection must be empty or `T` must either be
        ///    `SendSync` or `Local`.
        /// 3. If `C` is a `Sized` type: The contexts contained in all of the
        ///    reports in the `Vec` are of type `C`.
        /// 4. All references to these reports or any sub-reports are compatible
        ///    with shared ownership. Specifically there are no references with
        ///    an assumption that the strong_count is `1`.
        /// 5. If `T = SendSync`: All contexts and attachments in all of the
        ///    reports and all sub-reports must be `Send+Sync`
        #[must_use]
        pub(crate) unsafe fn from_raw_ref(raw: &Vec<RawReport>) -> &Self {
            // SAFETY: We must uphold the safety invariants of the raw field:
            // 1. Guaranteed by the caller
            // 2. Guaranteed by the caller
            // 3. Guaranteed by the caller
            // 4. Guaranteed by the caller
            // 5. Guaranteed by the caller
            // 6. Not applicable
            let raw_ptr = core::ptr::from_ref(raw).cast::<Self>();

            // SAFETY:
            // - The raw pointer is derived from a valid reference with the same lifetime
            //   and representation
            // - Creating this reference does not violate any aliasing rules as we are only
            //   creating a shared reference
            // - The type invariants of `Self` are upheld as per the caller's guarantee
            unsafe { &*raw_ptr }
        }

        /// Creates a mutable reference to a [`ReportCollection`] from mutable
        /// reference
        ///
        /// # Safety
        ///
        /// The caller must ensure:
        ///
        /// 1. Either the collection must be empty, `C` must either be a type
        ///    bounded by `Sized`, or C must be `Dynamic`.
        /// 2. Either the collection must be empty or `T` must either be
        ///    `SendSync` or `Local`.
        /// 3. If `C` is a `Sized` type: The contexts contained in all of the
        ///    reports in the `Vec` are of type `C`.
        /// 4. All references to these reports or any sub-reports are compatible
        ///    with shared ownership. Specifically there are no references with
        ///    an assumption that the strong_count is `1`.
        /// 5. If `T = SendSync`: All contexts and attachments in all of the
        ///    reports and all sub-reports must be `Send+Sync`
        #[must_use]
        pub(crate) unsafe fn from_raw_mut(raw: &mut Vec<RawReport>) -> &mut Self {
            // SAFETY: We must uphold the safety invariants of the raw field:
            // 1. Guaranteed by the caller
            // 2. Guaranteed by the caller
            // 3. Guaranteed by the caller
            // 4. Guaranteed by the caller
            // 5. Guaranteed by the caller
            // 6. We are not mutating the vector here, so the invariant is upheld here.
            let raw_ptr = core::ptr::from_mut(raw).cast::<Self>();

            // SAFETY:
            // - The raw pointer is derived from a valid reference with the same lifetime
            //   and representation
            // - Creating this reference does not violate any aliasing rules as we are only
            //   creating a mutable reference from a different reference that is no longer
            //   being used.
            // - The type invariants of `Self` are upheld as per the caller's guarantee
            unsafe { &mut *raw_ptr }
        }

        /// Consumes the [`ReportCollection`] and returns the inner raw reports
        #[must_use]
        pub(crate) fn into_raw(self) -> Vec<RawReport> {
            // SAFETY: We are destroying `self`, so we no longer
            // need to uphold invariants 1-5. Invariant 6 is not relevant as
            // we are consuming self and thus could not have been created through
            // `from_raw_mut`.
            self.raw
        }

        /// Provides access to the inner raw reports vector
        #[must_use]
        pub(crate) fn as_raw(&self) -> &Vec<RawReport> {
            // SAFETY: We must uphold the safety invariants of the raw field:
            // 1. Upheld as the type parameters do not change.
            // 2. Upheld as the type parameters do not change.
            // 3. Upheld, as we are not allowing mutation
            // 4. Upheld, as we are not creating any such references
            // 5. Upheld, as we are not allowing mutation
            // 6. Not applicable, as we are not allowing mutation
            &self.raw
        }

        /// Provides mutable access to the inner raw reports vector
        ///
        /// # Safety
        ///
        /// The caller must ensure:
        ///
        /// 1. If the collection is mutated so that it becomes non-empty, then
        ///    `C` must either be a type bounded by `Sized`, or be `Dynamic`.
        /// 2. If the collection is mutated so that it becomes non-empty, then
        ///    `T` must either be `SendSync` or `Local`.
        /// 3. If `C` is a `Sized` type: No mutation is performed that would
        ///    invalidate the invariant that all contexts are of type `C`.
        /// 4. No mutation is performed that would invalidate the shared
        ///    ownership invariant.
        /// 5. If `T = SendSync`: No mutation is performed that invalidates the
        ///    invariant that all inner contexts and attachments are `Send +
        ///    Sync`.
        #[must_use]
        pub(crate) unsafe fn as_raw_mut(&mut self) -> &mut Vec<RawReport> {
            // SAFETY: We must uphold the safety invariants of the raw field:
            // 1. Guaranteed by the caller
            // 2. Guaranteed by the caller
            // 3. Guaranteed by the caller
            // 4. Guaranteed by the caller
            // 5. Guaranteed by the caller
            // 6. Guaranteed by the caller
            &mut self.raw
        }
    }
}
pub use limit_field_access::ReportCollection;

impl<C: ?Sized, T> ReportCollection<C, T> {
    /// Creates a new, empty `ReportCollection`.
    ///
    /// The collection will be initially empty and will have no capacity
    /// allocated. This method is equivalent to calling
    /// [`Default::default()`].
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::report_collection::ReportCollection;
    ///
    /// let collection: ReportCollection = ReportCollection::new();
    /// assert!(collection.is_empty());
    /// assert_eq!(collection.len(), 0);
    /// ```
    #[must_use]
    pub fn new() -> Self {
        let reports = Vec::new();
        // SAFETY:
        // 1. The vector is empty, so this is upheld.
        // 2. The vector is empty, so this is upheld.
        // 3. We just created the empty Vec, so the invariants are upheld for all
        //    reports in it.
        // 4. We just created the empty Vec, so the invariants are upheld for all
        //    reports in it.
        // 5. We just created the empty Vec, so the invariants are upheld for all
        //    reports in it.
        unsafe { Self::from_raw(reports) }
    }

    /// Creates a new, empty `ReportCollection` with the specified capacity.
    ///
    /// The collection will be able to hold at least `capacity` reports without
    /// reallocating. If you plan to add a known number of reports to the
    /// collection, using this method can help improve performance by reducing
    /// the number of memory allocations needed.
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::report_collection::ReportCollection;
    ///
    /// let collection: ReportCollection = ReportCollection::with_capacity(10);
    /// assert!(collection.is_empty());
    /// assert_eq!(collection.len(), 0);
    /// assert!(collection.capacity() >= 10);
    /// ```
    pub fn with_capacity(capacity: usize) -> Self {
        let reports = Vec::with_capacity(capacity);
        // SAFETY: We just created the empty Vec, so there are no reports in it.
        // 1. No reports, so the invariants are upheld.
        // 2. No reports, so the invariants are upheld.
        // 3. No reports, so the invariants are upheld.
        // 4. No reports, so the invariants are upheld.
        // 5. No reports, so the invariants are upheld.
        unsafe { Self::from_raw(reports) }
    }

    /// Appends a report to the end of the collection.
    ///
    /// This method takes ownership of the report and adds it to the collection.
    /// The report must have the [`Cloneable`] ownership marker, which allows it
    /// to be stored in the collection and cloned when needed.
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::{report, report_collection::ReportCollection};
    ///
    /// let mut collection = ReportCollection::new();
    /// let report = report!("An error occurred").into_cloneable();
    ///
    /// collection.push(report);
    /// assert_eq!(collection.len(), 1);
    /// ```
    pub fn push(&mut self, report: Report<C, Cloneable, T>) {
        // SAFETY:
        // 1. The invariants of the pushed report guarantee this.
        // 2. The invariants of the pushed report guarantee that `T` is either `Local`
        //    or `SendSync`.
        // 3. The invariants of the pushed report guarantee this.
        // 4. The argument has `O=Cloneable`, so the invariants of the pushed report
        //    guarantee this.
        // 5. If `T = SendSync`: The invariants of the pushed report guarantee this.
        let raw = unsafe { self.as_raw_mut() };

        raw.push(report.into_raw())
    }

    /// Removes and returns the last report from the collection.
    ///
    /// Returns [`None`] if the collection is empty.
    ///
    /// This method provides LIFO (last in, first out) behavior, making the
    /// collection behave like a stack for the most recently added reports.
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::{report, report_collection::ReportCollection};
    ///
    /// let mut collection = ReportCollection::new();
    /// let report1 = report!("First error").into_cloneable();
    /// let report2 = report!("Second error").into_cloneable();
    ///
    /// collection.push(report1);
    /// collection.push(report2);
    ///
    /// let last_report = collection.pop().unwrap();
    /// assert_eq!(collection.len(), 1);
    ///
    /// let empty_pop = ReportCollection::<&str>::new().pop();
    /// assert!(empty_pop.is_none());
    /// ```
    pub fn pop(&mut self) -> Option<Report<C, Cloneable, T>> {
        // SAFETY:
        // 1. If the collection is already non-empty, `C` is already valid. Otherwise
        //    this will not modify it to become non-empty.
        // 2. If the collection is already non-empty, `T` is already valid. Otherwise
        //    this will not modify it to become non-empty.
        // 3. Removing an element does not change the types of contexts in the remaining
        //    elements.
        // 4. Removing an element does not invalidate the shared ownership properties of
        //    the remaining elements.
        // 5. Removing an element does not cause the remaining elements to stop being
        //    `Send + Sync`.
        let raw = unsafe { self.as_raw_mut() };

        let report = raw.pop()?;

        // SAFETY:
        // 1. Guaranteed by the invariants of the collection.
        // 2. `O=Cloneable`, so this is trivially true.
        // 3. Guaranteed by the invariants of the collection.
        // 4. If `C` is a `Sized` type: Guaranteed by the invariants of the collection.
        // 5. `O=Cloneable`, so this is trivially true.
        // 6. Guaranteed by the invariants of the collection.
        // 7. Guaranteed by the invariants of the collection.
        // 8. If `T = SendSync`: Guaranteed by the invariants of the collection.
        let report = unsafe { Report::<C, Cloneable, T>::from_raw(report) };

        Some(report)
    }

    /// Returns the number of reports in the collection.
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::{report, report_collection::ReportCollection};
    ///
    /// let mut collection = ReportCollection::new();
    /// assert_eq!(collection.len(), 0);
    ///
    /// collection.push(report!("Error 1").into_cloneable());
    /// collection.push(report!("Error 2").into_cloneable());
    /// assert_eq!(collection.len(), 2);
    /// ```
    #[must_use]
    pub fn len(&self) -> usize {
        self.as_raw().len()
    }

    /// Returns the capacity of the collection.
    ///
    /// The capacity is the number of reports the collection can hold without
    /// allocating additional memory.
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::{
    ///     markers::{Dynamic, SendSync},
    ///     report,
    ///     report_collection::ReportCollection,
    /// };
    ///
    /// let collection = ReportCollection::<Dynamic, SendSync>::with_capacity(5);
    /// assert!(collection.capacity() <= 5);
    /// ```
    pub fn capacity(&self) -> usize {
        self.as_raw().capacity()
    }

    /// Reserves capacity for at least `additional` more reports to be inserted
    /// in the collection.
    ///
    /// The collection may reserve more space to avoid frequent reallocations.
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::{
    ///     markers::{Dynamic, SendSync},
    ///     report,
    ///     report_collection::ReportCollection,
    /// };
    ///
    /// let mut collection = ReportCollection::<Dynamic, SendSync>::new();
    /// collection.reserve(10);
    /// assert!(collection.capacity() >= 10);
    /// ```
    pub fn reserve(&mut self, additional: usize) {
        // SAFETY:
        // 1. We only reserve space, so the invariants of the collection remain upheld.
        // 2. We only reserve space, so the invariants of the collection remain upheld.
        // 3. We only reserve space, so the invariants of the collection remain upheld.
        // 4. We only reserve space, so the invariants of the collection remain upheld.
        // 5. We only reserve space, so the invariants of the collection remain upheld.
        let raw = unsafe { self.as_raw_mut() };

        raw.reserve(additional)
    }

    /// Returns a reference to the report at the given index.
    ///
    /// Returns [`None`] if the index is out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::{report, report_collection::ReportCollection};
    ///
    /// let mut collection = ReportCollection::new();
    /// collection.push(report!("First error").into_cloneable());
    /// collection.push(report!("Second error").into_cloneable());
    ///
    /// let first_report = collection.get(0).unwrap();
    /// let second_report = collection.get(1).unwrap();
    /// let out_of_bounds = collection.get(2);
    ///
    /// assert!(out_of_bounds.is_none());
    /// ```
    #[must_use]
    pub fn get(&self, index: usize) -> Option<ReportRef<'_, C, Cloneable, T>> {
        let raw = self.as_raw().get(index)?.as_ref();

        // SAFETY:
        // 1. Guaranteed by the invariants of the collection.
        // 2. `O=Cloneable`, so this is trivially true.
        // 3. Guaranteed by the invariants of the collection.
        // 4. If `C` is a `Sized` type: Guaranteed by the invariants of the collection.
        // 5. Guaranteed by the invariants of the collection.
        // 6. Guaranteed by the invariants of the collection.
        // 7. If `T = SendSync`: Guaranteed by the invariants of the collection.
        let report = unsafe { ReportRef::<C, Cloneable, T>::from_raw(raw) };

        Some(report)
    }

    /// Returns `true` if the collection contains no reports.
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::{report, report_collection::ReportCollection};
    ///
    /// let mut collection = ReportCollection::new();
    /// assert!(collection.is_empty());
    ///
    /// collection.push(report!("An error").into_cloneable());
    /// assert!(!collection.is_empty());
    /// ```
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.as_raw().is_empty()
    }

    /// Returns an iterator over references to the reports in the collection.
    ///
    /// The iterator yields [`ReportRef`] items, which are lightweight
    /// references to the reports in the collection.
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::{report, report_collection::ReportCollection};
    ///
    /// let mut collection = ReportCollection::new();
    /// collection.push(report!("Error 1").into_cloneable());
    /// collection.push(report!("Error 2").into_cloneable());
    ///
    /// for (i, report_ref) in collection.iter().enumerate() {
    ///     println!("Report {}: {}", i, report_ref);
    /// }
    /// ```
    pub fn iter(&self) -> ReportCollectionIter<'_, C, T> {
        let raw = self.as_raw();

        // SAFETY:
        // 1. Guaranteed by the invariants of the collection.
        // 2. Guaranteed by the invariants of the collection.
        // 3. Guaranteed by the invariants of the collection.
        // 4. Guaranteed by the invariants of the collection.
        // 5. Guaranteed by the invariants of the collection.
        unsafe { ReportCollectionIter::from_raw(raw) }
    }

    /// Formats the entire collection using a specific report formatting hook.
    ///
    /// This method allows you to format a collection of reports with a custom
    /// formatter without globally registering it. This is useful for:
    /// - One-off custom formatting
    /// - Testing different formatters
    /// - Using different formatters in different parts of your application
    ///
    /// Unlike the default `Display` and `Debug` implementations which use the
    /// globally registered hook, this method uses the hook you provide
    /// directly.
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::{
    ///     hooks::builtin_hooks::report_formatter::DefaultReportFormatter, report,
    ///     report_collection::ReportCollection,
    /// };
    ///
    /// let mut collection = ReportCollection::new();
    /// collection.push(report!("Error 1").into_cloneable());
    /// collection.push(report!("Error 2").into_cloneable());
    ///
    /// // Format with ASCII-only output (no Unicode or ANSI colors)
    /// let formatted = collection.format_with(&DefaultReportFormatter::ASCII);
    /// println!("{}", formatted);
    /// ```
    #[must_use]
    pub fn format_with<H>(&self, hook: &H) -> impl core::fmt::Display + core::fmt::Debug
    where
        H: crate::hooks::report_formatter::ReportFormatter,
    {
        let raw = self.as_raw();

        // SAFETY:
        // 1. `C=Dynamic`, so this is trivially true.
        // 2. `O=Uncloneable`, so this is trivially true.
        // 3. `T=Local`, so this is trivially true.
        // 4. For the called method we set `C=Dynamic`, so this is trivially true.
        // 5. For the called method we set `O=Uncloneable`, so this is trivially true.
        // 6. Guaranteed by the invariants of the collection.
        // 7. For the called method we set `T=Local`, so this is trivially true.
        let slice = unsafe {
            // @add-unsafe-context: Dynamic
            // @add-unsafe-context: rootcause_internals::RawReport
            // @add-unsafe-context: rootcause_internals::RawReportRef
            ReportRef::<Dynamic, Uncloneable, Local>::from_raw_slice(raw)
        };

        crate::util::format_helper(
            (slice, hook),
            |(slice, hook), formatter| {
                hook.format_reports(slice, formatter, FormattingFunction::Display)
            },
            |(slice, hook), formatter| {
                hook.format_reports(slice, formatter, FormattingFunction::Debug)
            },
        )
    }

    /// Converts the collection to use type-erased contexts via [`Dynamic`].
    ///
    /// This performs type erasure on the context type parameter, allowing
    /// collections with different concrete context types to be stored
    /// together or passed to functions that accept `ReportCollection<Dynamic,
    /// T>`.
    ///
    /// This method does not actually modify the collection in any way. It only
    /// has the effect of "forgetting" that the context actually has the
    /// type `C`.
    ///
    /// The thread safety marker `T` is preserved during this conversion.
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::{markers::Dynamic, report, report_collection::ReportCollection};
    ///
    /// let mut collection: ReportCollection<Dynamic> = ReportCollection::new();
    /// collection.push(report!("String error").into_cloneable());
    ///
    /// let erased: ReportCollection<Dynamic> = collection.into_dynamic();
    /// assert_eq!(erased.len(), 1);
    /// ```
    #[must_use]
    pub fn into_dynamic(self) -> ReportCollection<Dynamic, T> {
        let raw = self.into_raw();

        // SAFETY:
        // 1. The invariants of the collection guarantee this.
        // 2. The invariants of the collection guarantee this.
        // 3. `C=Dynamic`, so this is trivially true.
        // 4. The invariants of the collection guarantee this.
        // 5. The invariants of the collection guarantee this.
        unsafe {
            // @add-unsafe-context: Dynamic
            ReportCollection::<Dynamic, T>::from_raw(raw)
        }
    }

    /// Returns a reference to the collection with type-erased contexts via
    /// [`Dynamic`].
    #[must_use]
    pub fn as_dynamic(&self) -> &ReportCollection<Dynamic, T> {
        let raw = self.as_raw();

        // SAFETY:
        // 1. The invariants of the collection guarantee this.
        // 2. The invariants of the collection guarantee this.
        // 3. `C=Dynamic`, so this is trivially true.
        // 4. The invariants of the collection guarantee this.
        // 5. The invariants of the collection guarantee this.
        unsafe {
            // @add-unsafe-context: Dynamic
            ReportCollection::<Dynamic, T>::from_raw_ref(raw)
        }
    }

    /// Converts the collection to use [`Local`] thread safety semantics.
    ///
    /// This changes the thread safety marker from any type to [`Local`], which
    /// means the resulting collection will not implement [`Send`] or
    /// [`Sync`]. This is useful when you want to use the collection in
    /// single-threaded contexts and potentially store non-thread-safe data.
    ///
    /// This method does not actually modify the collection in any way. It only
    /// has the effect of "forgetting" that all objects in the
    /// [`ReportCollection`] are actually [`Send`] and [`Sync`].
    ///
    /// The context type `C` is preserved during this conversion.
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::{
    ///     markers::{Dynamic, Local},
    ///     report,
    ///     report_collection::ReportCollection,
    /// };
    ///
    /// let mut collection: ReportCollection<Dynamic> = ReportCollection::new(); // defaults to SendSync
    /// collection.push(report!("An error").into_cloneable());
    ///
    /// let local_collection: ReportCollection<Dynamic, Local> = collection.into_local();
    /// assert_eq!(local_collection.len(), 1);
    /// ```
    #[must_use]
    pub fn into_local(self) -> ReportCollection<C, Local> {
        let raw = self.into_raw();

        // SAFETY:
        // 1. The invariants of the collection guarantee this.
        // 2. `T=Local`, so this is trivially true.
        // 3. The invariants of the collection guarantee this.
        // 4. The invariants of the collection guarantee this.
        // 5. `T=Local`, so this is trivially true.
        unsafe { ReportCollection::<C, Local>::from_raw(raw) }
    }

    /// Returns a reference to the collection with [`Local`] thread safety
    /// semantics.
    #[must_use]
    pub fn as_local(&self) -> &ReportCollection<C, Local> {
        let raw = self.as_raw();

        // SAFETY:
        // 1. The invariants of the collection guarantee this.
        // 2. `T=Local`, so this is trivially true.
        // 3. The invariants of the collection guarantee this.
        // 4. The invariants of the collection guarantee this.
        // 5. `T=Local`, so this is trivially true.
        unsafe { ReportCollection::<C, Local>::from_raw_ref(raw) }
    }

    /// Creates a new [`Report`] with the given context and sets the current
    /// report collection as the children of the new report.
    ///
    /// The new context will use the [`handlers::Display`] handler to format the
    /// context.
    ///
    /// This is a convenience method used for chaining method calls; it consumes
    /// the [`ReportCollection`] and returns a new [`Report`].
    ///
    /// If you want a different context handler, you can use
    /// [`Report::context_custom`].
    ///
    /// If you want to more directly control the allocation of the new report,
    /// you can use [`Report::from_parts`], which is the underlying method
    /// used to implement this method.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{Report, report_collection::ReportCollection, report};
    /// let report_collection: ReportCollection = [report!("error A"), report!("error B")]
    ///     .into_iter()
    ///     .collect();
    /// let report: Report<&str> = report_collection.context("additional context");
    /// ```
    #[track_caller]
    #[must_use]
    pub fn context<D>(self, context: D) -> Report<D, Mutable, T>
    where
        D: markers::ObjectMarkerFor<T> + core::fmt::Display + core::fmt::Debug,
    {
        self.context_custom::<handlers::Display, _>(context)
    }

    /// Creates a new [`Report`] with the given context and sets the current
    /// report collection as the children of the new report.
    ///
    /// This is a convenience method used for chaining method calls; it consumes
    /// the [`ReportCollection`] and returns a [`Report`].
    ///
    /// If you want to more directly control the allocation of the new report,
    /// you can use [`Report::from_parts`], which is the underlying method
    /// used to implement this method.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{Report, report_collection::ReportCollection, report, handlers};
    /// let report_collection: ReportCollection = [report!("error A"), report!("error B")]
    ///     .into_iter()
    ///     .collect();
    /// let report: Report<&str> = report_collection.context_custom::<handlers::Debug, _>("context");
    /// ```
    #[track_caller]
    #[must_use]
    pub fn context_custom<H, D>(self, context: D) -> Report<D, Mutable, T>
    where
        D: markers::ObjectMarkerFor<T>,
        H: ContextHandler<D>,
    {
        Report::from_parts::<H>(context, self.into_dynamic(), ReportAttachments::new())
    }
}

impl<C: ?Sized> ReportCollection<C, SendSync> {
    /// Creates a new, empty `ReportCollection` with [`SendSync`] thread safety.
    ///
    /// This is equivalent to calling [`new()`](Self::new) but makes the thread
    /// safety marker explicit. The resulting collection can be safely sent
    /// between threads and shared across threads.
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::{markers::SendSync, report_collection::ReportCollection};
    ///
    /// let collection: ReportCollection<&str, SendSync> = ReportCollection::new_sendsync();
    /// assert!(collection.is_empty());
    /// ```
    #[must_use]
    pub fn new_sendsync() -> Self {
        Self::new()
    }
}

impl<C: ?Sized> ReportCollection<C, Local> {
    /// Creates a new, empty `ReportCollection` with [`Local`] thread safety.
    ///
    /// This creates a collection that is not [`Send`] or [`Sync`], meaning it
    /// cannot be transferred between threads or shared across threads. This
    /// is useful for single-threaded applications or when you need to store
    /// non-thread-safe data.
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::{markers::Local, report_collection::ReportCollection};
    ///
    /// let collection: ReportCollection<&str, Local> = ReportCollection::new_local();
    /// assert!(collection.is_empty());
    /// ```
    #[must_use]
    pub fn new_local() -> Self {
        Self::new()
    }
}

impl<C: ?Sized> Default for ReportCollection<C, SendSync> {
    fn default() -> Self {
        Self::new_sendsync()
    }
}

impl<C: ?Sized> Default for ReportCollection<C, Local> {
    fn default() -> Self {
        Self::new_local()
    }
}

impl<C: ?Sized, O, T> Extend<Report<C, O, T>> for ReportCollection<C, T>
where
    O: markers::ReportOwnershipMarker,
{
    fn extend<I: IntoIterator<Item = Report<C, O, T>>>(&mut self, iter: I) {
        let iter = iter.into_iter();
        self.reserve(iter.size_hint().0);
        for report in iter {
            self.push(report.into_cloneable());
        }
    }
}

impl<C: Sized, O, T> Extend<Report<C, O, T>> for ReportCollection<Dynamic, T>
where
    O: markers::ReportOwnershipMarker,
{
    fn extend<I: IntoIterator<Item = Report<C, O, T>>>(&mut self, iter: I) {
        let iter = iter.into_iter();
        self.reserve(iter.size_hint().0);
        for report in iter {
            self.push(report.into_dynamic().into_cloneable());
        }
    }
}

impl<'a, C: ?Sized, T> Extend<ReportRef<'a, C, Cloneable, T>> for ReportCollection<C, T> {
    fn extend<I: IntoIterator<Item = ReportRef<'a, C, Cloneable, T>>>(&mut self, iter: I) {
        let iter = iter.into_iter();
        self.reserve(iter.size_hint().0);
        for report in iter {
            self.push(report.clone_arc());
        }
    }
}

impl<'a, C: Sized, T> Extend<ReportRef<'a, C, Cloneable, T>> for ReportCollection<Dynamic, T> {
    fn extend<I: IntoIterator<Item = ReportRef<'a, C, Cloneable, T>>>(&mut self, iter: I) {
        let iter = iter.into_iter();
        self.reserve(iter.size_hint().0);
        for report in iter {
            self.push(report.clone_arc().into_dynamic());
        }
    }
}

impl<C: ?Sized, O, T> FromIterator<Report<C, O, T>> for ReportCollection<C, T>
where
    O: markers::ReportOwnershipMarker,
{
    fn from_iter<I: IntoIterator<Item = Report<C, O, T>>>(iter: I) -> Self {
        let mut siblings = ReportCollection::<C, T>::new();
        siblings.extend(iter);
        siblings
    }
}

impl<C: Sized, O, T> FromIterator<Report<C, O, T>> for ReportCollection<Dynamic, T>
where
    O: markers::ReportOwnershipMarker,
{
    fn from_iter<I: IntoIterator<Item = Report<C, O, T>>>(iter: I) -> Self {
        let mut siblings = ReportCollection::new();
        siblings.extend(iter);
        siblings
    }
}

impl<'a, C: ?Sized, T> FromIterator<ReportRef<'a, C, Cloneable, T>> for ReportCollection<C, T> {
    fn from_iter<I: IntoIterator<Item = ReportRef<'a, C, Cloneable, T>>>(iter: I) -> Self {
        let mut siblings = ReportCollection::new();
        siblings.extend(iter);
        siblings
    }
}

impl<'a, C: Sized, T> FromIterator<ReportRef<'a, C, Cloneable, T>>
    for ReportCollection<Dynamic, T>
{
    fn from_iter<I: IntoIterator<Item = ReportRef<'a, C, Cloneable, T>>>(iter: I) -> Self {
        let mut siblings = ReportCollection::new();
        siblings.extend(iter);
        siblings
    }
}

impl<C: ?Sized, T> core::fmt::Display for ReportCollection<C, T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let raw = self.as_raw();

        // SAFETY:
        // 1. `C=Dynamic`, so this is trivially true.
        // 2. `O=Uncloneable`, so this is trivially true.
        // 3. `T=Local`, so this is trivially true.
        // 4. For the called method we set `C=Dynamic`, so this is trivially true.
        // 5. For the called method we set `O=Uncloneable`, so this is trivially true.
        // 6. Guaranteed by the invariants of the collection.
        // 7. For the called method we set `T=Local`, so this is trivially true.
        let slice = unsafe {
            // @add-unsafe-context: rootcause_internals::RawReport
            // @add-unsafe-context: rootcause_internals::RawReportRef
            // @add-unsafe-context: Dynamic
            ReportRef::<Dynamic, Uncloneable, Local>::from_raw_slice(raw)
        };

        crate::hooks::report_formatter::format_reports(slice, f, FormattingFunction::Display)
    }
}

impl<C: ?Sized, T> core::fmt::Debug for ReportCollection<C, T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let raw = self.as_raw();

        // SAFETY:
        // 1. `C=Dynamic`, so this is trivially true.
        // 2. `O=Uncloneable`, so this is trivially true.
        // 3. `T=Local`, so this is trivially true.
        // 4. For the called method we set `C=Dynamic`, so this is trivially true.
        // 5. For the called method we set `O=Uncloneable`, so this is trivially true.
        // 6. Guaranteed by the invariants of the collection.
        // 7. For the called method we set `T=Local`, so this is trivially true.
        let slice = unsafe {
            // @add-unsafe-context: Dynamic
            // @add-unsafe-context: rootcause_internals::RawReport
            // @add-unsafe-context: rootcause_internals::RawReportRef
            ReportRef::<Dynamic, Uncloneable, Local>::from_raw_slice(raw)
        };

        crate::hooks::report_formatter::format_reports(slice, f, FormattingFunction::Debug)
    }
}

macro_rules! from_impls {
    ($(
        <
            $($param:ident),*
        >:
        $context1:ty => $context2:ty,
        $thread_safety1:ty => $thread_safety2:ty,
        [$($op:ident),*]
    ),* $(,)?) => {
        $(
            impl<$($param),*> From<ReportCollection<$context1, $thread_safety1>> for ReportCollection<$context2, $thread_safety2>
            {
                fn from(report_collection: ReportCollection<$context1, $thread_safety1>) -> Self {
                    report_collection
                        $(
                            .$op()
                        )*
                }
            }
        )*
    };
}

from_impls! {
    <C>: C => C, SendSync => Local, [into_local],
    <C>: C => Dynamic, SendSync => SendSync, [into_dynamic],
    <C>: C => Dynamic, SendSync => Local, [into_dynamic, into_local],
    <C>: C => Dynamic, Local => Local, [into_dynamic],
    <>: Dynamic => Dynamic, SendSync => Local, [into_local],
}

impl<C: ?Sized, T> From<Vec<Report<C, Cloneable, T>>> for ReportCollection<C, T> {
    fn from(reports: Vec<Report<C, Cloneable, T>>) -> Self {
        reports.into_iter().collect()
    }
}

impl<const N: usize, C: ?Sized, T> From<[Report<C, Cloneable, T>; N]> for ReportCollection<C, T> {
    fn from(reports: [Report<C, Cloneable, T>; N]) -> Self {
        reports.into_iter().collect()
    }
}

impl<C: ?Sized, T> Unpin for ReportCollection<C, T> {}

// SAFETY: The `SendSync` marker guarantees that all reports are `Send + Sync`
// so the collection can safely implement `Send` and `Sync`.
unsafe impl<C: ?Sized> Send for ReportCollection<C, SendSync> {}

// SAFETY: The `SendSync` marker guarantees that all reports are `Send + Sync`
// so the collection can safely implement `Send` and `Sync`.
unsafe impl<C: ?Sized> Sync for ReportCollection<C, SendSync> {}

impl<C: ?Sized, T> IntoIterator for ReportCollection<C, T> {
    type IntoIter = ReportCollectionIntoIter<C, T>;
    type Item = Report<C, Cloneable, T>;

    fn into_iter(self) -> Self::IntoIter {
        let raw = self.into_raw();

        // SAFETY:
        // 1. Guaranteed by the invariants of the collection.
        // 2. Guaranteed by the invariants of the collection.
        // 3. Guaranteed by the invariants of the collection.
        // 4. Guaranteed by the invariants of the collection.
        // 5. Guaranteed by the invariants of the collection.
        unsafe { ReportCollectionIntoIter::<C, T>::from_raw(raw) }
    }
}

impl<'a, C: ?Sized, T> IntoIterator for &'a ReportCollection<C, T> {
    type IntoIter = ReportCollectionIter<'a, C, T>;
    type Item = ReportRef<'a, C, Cloneable, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<C: ?Sized, T> Clone for ReportCollection<C, T> {
    fn clone(&self) -> Self {
        self.iter().map(|child| child.clone_arc()).collect()
    }
}

#[cfg(test)]
mod tests {
    use alloc::string::String;

    use super::*;

    #[allow(dead_code)]
    struct NonSend(*const ());
    static_assertions::assert_not_impl_any!(NonSend: Send, Sync);

    #[test]
    fn test_report_collection_send_sync() {
        static_assertions::assert_impl_all!(ReportCollection<(), SendSync>: Send, Sync);
        static_assertions::assert_impl_all!(ReportCollection<String, SendSync>: Send, Sync);
        static_assertions::assert_impl_all!(ReportCollection<NonSend, SendSync>: Send, Sync); // This still makes sense, since you won't actually be able to construct this report
        static_assertions::assert_impl_all!(ReportCollection<Dynamic, SendSync>: Send, Sync);

        static_assertions::assert_not_impl_any!(ReportCollection<(), Local>: Send, Sync);
        static_assertions::assert_not_impl_any!(ReportCollection<String, Local>: Send, Sync);
        static_assertions::assert_not_impl_any!(ReportCollection<NonSend, Local>: Send, Sync);
        static_assertions::assert_not_impl_any!(ReportCollection<Dynamic, Local>: Send, Sync);
    }

    #[test]
    fn test_report_collection_unpin() {
        static_assertions::assert_impl_all!(ReportCollection<(), SendSync>: Unpin);
        static_assertions::assert_impl_all!(ReportCollection<String, SendSync>: Unpin);
        static_assertions::assert_impl_all!(ReportCollection<NonSend, SendSync>: Unpin); // This still makes sense, since you won't actually be able to construct this report
        static_assertions::assert_impl_all!(ReportCollection<Dynamic, SendSync>: Unpin);

        static_assertions::assert_impl_all!(ReportCollection<(), Local>: Unpin);
        static_assertions::assert_impl_all!(ReportCollection<String, Local>: Unpin);
        static_assertions::assert_impl_all!(ReportCollection<NonSend, Local>: Unpin);
        static_assertions::assert_impl_all!(ReportCollection<Dynamic, Local>: Unpin);
    }

    #[test]
    fn test_report_collection_copy_clone() {
        static_assertions::assert_impl_all!(ReportCollection<(), SendSync>: Clone);
        static_assertions::assert_impl_all!(ReportCollection<String, SendSync>: Clone);
        static_assertions::assert_impl_all!(ReportCollection<NonSend, SendSync>: Clone); // This still makes sense, since you won't actually be able to construct this report
        static_assertions::assert_impl_all!(ReportCollection<Dynamic, SendSync>: Clone);

        static_assertions::assert_impl_all!(ReportCollection<(), Local>: Clone);
        static_assertions::assert_impl_all!(ReportCollection<String, Local>: Clone);
        static_assertions::assert_impl_all!(ReportCollection<NonSend, Local>: Clone);
        static_assertions::assert_impl_all!(ReportCollection<Dynamic, Local>: Clone);

        static_assertions::assert_not_impl_any!(ReportCollection<(), SendSync>: Copy);
        static_assertions::assert_not_impl_any!(ReportCollection<String, SendSync>: Copy);
        static_assertions::assert_not_impl_any!(ReportCollection<NonSend, SendSync>: Copy); // This still makes sense, since you won't actually be able to construct this report_collection collection
        static_assertions::assert_not_impl_any!(ReportCollection<Dynamic, SendSync>: Copy);

        static_assertions::assert_not_impl_any!(ReportCollection<(), Local>: Copy);
        static_assertions::assert_not_impl_any!(ReportCollection<String, Local>: Copy);
        static_assertions::assert_not_impl_any!(ReportCollection<NonSend, Local>: Copy);
        static_assertions::assert_not_impl_any!(ReportCollection<Dynamic, Local>: Copy);
    }
}