ocpi-tariffs 0.20.0

OCPI tariff calculations
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
//! These types are the basis for writing functions that can emit a set of [`Warning`]s based on the value they are trying to create.
//!
//! The aim is for functions to be as resilient as possible while creating the value and emit commentary on their progress in the form of a growing set of [`Warning`]s.
//!
//! The caller of the function can use the set of [`Warning`]s to decide whether the operation was a success or failure and whether the value can be used or needs to be modified.
//!  
//! A concrete example is the conversion of a JSON [`json::Element`] into a `country::Code`. The [`json::Element`] may be the incorrect type and so the function issues a [`Warning`] and exits as it cannot continue with the given data. The signature of this fn is something like:
//!
//! ```rust ignore
//! // file: country.rs
//!  
//! pub enum Warning {
//!     InvalidType,
//!     ...
//! }
//!
//! pub enum Expect {
//!     Alpha2,
//!     Alpha3
//! }
//!
//! pub enum Code {
//!     fn from_json_element(json: json::Element, expect: Expect) -> Verdict<Code, Warning> {
//!         ...
//!     }
//! }
//! ```
//!
//! A [`Verdict`] is a [`Result`] where both the `Ok` and `Err` variants return a potential set of [`Warning`]s.
//! The `Ok` variant is `Caveat<T>`, where a [`Caveat`] contains a value but potentially contains cautionary details to be taken into account when using the value.
//! Hence the name.
//!
//! The `Err` variant is `Warnings<K>`, a collection of [`Warning`]s. A [`Warning`] can be converted into an `Error` by the caller. A `Caveat<T>` is more completely described as `Caveat<T, K>` where the `Caveat` contains a value `T` and a set of `Warnings<K>`.
//!
//! All of this is to say that a resilient function can always return [`Warning`]s and the caller can gather them
//! together into a new set or fail.
//!
//! Returning to the example of the [`country::Code`](crate::country::Code), if the [`json::Element`] is the expected string type, then processing continues.
//! The string may contain control chars or escape chars and both these cases will emit a [`Warning`].
//! The string may be made up of three chars when two were expected.
//! This is the interesting case, as some [`country::Code`](crate::country::Code) fields are `alpha-3` where others are `alpha-2`.
//! Processing can still continue, as an `alpha-3` code can be converted to an `alpha-2` simply, while emitting a [`Warning`].
//!
//! The caller can decide whether this is acceptable or not.

use std::{borrow::Cow, fmt, slice};

use tracing::error;

use crate::json;

/// Implement `IntoCaveat` for the given type so that it can take part in the `Warning` system.
#[doc(hidden)]
#[macro_export]
macro_rules! into_caveat {
    ($kind:ident<$life:lifetime>) => {
        impl<$life> IntoCaveat for $kind<$life> {
            fn into_caveat<K: $crate::warning::Kind>(
                self,
                warnings: $crate::warning::Set<K>,
            ) -> $crate::Caveat<Self, K> {
                $crate::Caveat::new(self, warnings)
            }
        }
    };
    ($kind:path) => {
        impl IntoCaveat for $kind {
            fn into_caveat<K: $crate::warning::Kind>(
                self,
                warnings: $crate::warning::Set<K>,
            ) -> $crate::Caveat<Self, K> {
                $crate::Caveat::new(self, warnings)
            }
        }
    };
}

/// Implement `IntoCaveat` for the given type so that it can take part in the `Warning` system.
macro_rules! into_caveat_all {
    ($($kind:ty),+) => {
        $(impl IntoCaveat for $kind {
            fn into_caveat<K: Kind>(
                self,
                warnings: Set<K>,
            ) -> $crate::Caveat<Self, K> {
                $crate::Caveat::new(self, warnings)
            }
        })+
    };
}

/// A `Verdict` is a standard [`Result`] with [`Warning`]s potentially issued for both the `Ok` and `Err` variants.
pub type Verdict<T, K> = Result<Caveat<T, K>, Set<K>>;

/// A value that may have associated [`Warning`]s.
///
/// Even though the value has been created there may be certain caveats you should be aware of before using it.
#[derive(Debug)]
pub struct Caveat<T, K: Kind> {
    /// The value created by the function.
    value: T,

    /// A list of [`Warning`]s or caveats issued when creating the value.
    warnings: Set<K>,
}

impl<T, K> Caveat<T, K>
where
    T: IntoCaveat,
    K: Kind,
{
    /// The only way to create `Caveat<T>` is if `T` impls `IntoCaveat`.
    pub(crate) fn new(value: T, warnings: Set<K>) -> Self {
        Self { value, warnings }
    }
}

impl<T, K> Caveat<T, K>
where
    K: Kind,
{
    /// Return the value and any [`Warning`]s stored in the `Caveat`.
    pub fn into_parts(self) -> (T, Set<K>) {
        let Self { value, warnings } = self;
        (value, warnings)
    }

    /// Return the value and drop any warnings contained within.
    pub fn ignore_warnings(self) -> T {
        self.value
    }

    pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Caveat<U, K> {
        let Self { value, warnings } = self;
        Caveat {
            value: op(value),
            warnings,
        }
    }
}

/// Convert a `Caveat`-like type into a `T` by gathering up it's [`Warning`]s.
pub(crate) trait GatherWarnings<T, K>
where
    K: Kind,
{
    type Output;

    /// Convert a `Caveat`-like type into a `T` by gathering up it's [`Warning`]s.
    fn gather_warnings_into<KA>(self, warnings: &mut Set<KA>) -> Self::Output
    where
        K: Into<KA>,
        KA: Kind;
}

/// Convert a `Caveat<T>` into `T` by gathering up it's `Warning`s.
impl<T, K> GatherWarnings<T, K> for Caveat<T, K>
where
    K: Kind,
{
    type Output = T;

    /// Convert a `Caveat<T>` into `T` by gathering up it's `Warning`s.
    fn gather_warnings_into<KA>(self, warnings: &mut Set<KA>) -> Self::Output
    where
        K: Into<KA>,
        KA: Kind,
    {
        let Self {
            value,
            warnings: inner_warnings,
        } = self;

        warnings.0.extend(inner_warnings.0.into_iter().map(|warn| {
            let Warning { kind, elem_id } = warn;
            Warning {
                kind: kind.into(),
                elem_id,
            }
        }));

        value
    }
}

/// Convert a `Option<Caveat<T>>` into `Option<T>` by gathering up it's `Warning`s.
impl<T, K> GatherWarnings<T, K> for Option<Caveat<T, K>>
where
    K: Kind,
{
    type Output = Option<T>;

    /// Convert a `Caveat` related to type `T` into a `T` by gathering it's [`Warning`]s.
    fn gather_warnings_into<KA>(self, warnings: &mut Set<KA>) -> Self::Output
    where
        K: Into<KA>,
        KA: Kind,
    {
        match self {
            Some(cv) => Some(cv.gather_warnings_into(warnings)),
            None => None,
        }
    }
}

/// Convert a `Result<Caveat<T>>` into `Result<T>` by gathering up it's `Warning`s.
impl<T, K, E> GatherWarnings<T, K> for Result<Caveat<T, K>, E>
where
    K: Kind,
    E: std::error::Error,
{
    type Output = Result<T, E>;

    /// Convert a `Caveat` related to type `T` into a `T` by gathering it's [`Warning`]s.
    fn gather_warnings_into<KA>(self, warnings: &mut Set<KA>) -> Self::Output
    where
        K: Into<KA>,
        KA: Kind,
    {
        match self {
            Ok(cv) => Ok(cv.gather_warnings_into(warnings)),
            Err(err) => Err(err),
        }
    }
}

/// Convert a `Vec<Caveat<T>>` into `Vec<T>` by gathering up each elements `Warning`s.
impl<T, K> GatherWarnings<T, K> for Vec<Caveat<T, K>>
where
    K: Kind,
{
    type Output = Vec<T>;

    /// Convert a `Caveat` related to type `T` into a `T` by gathering it's [`Warning`]s.
    fn gather_warnings_into<KA>(self, warnings: &mut Set<KA>) -> Self::Output
    where
        K: Into<KA>,
        KA: Kind,
    {
        self.into_iter()
            .map(|cv| cv.gather_warnings_into(warnings))
            .collect()
    }
}

/// Converts a value `T` into a `Caveat`.
///
/// Each module can use this to whitelist their types for conversion to `Caveat<T>`.
pub trait IntoCaveat: Sized {
    /// Any type can be converted to `Caveat<T>` only a list of [`Warning`]s is required.
    fn into_caveat<K: Kind>(self, warnings: Set<K>) -> Caveat<Self, K>;
}

into_caveat_all!(
    (),
    bool,
    char,
    u8,
    u16,
    u32,
    u64,
    u128,
    i8,
    i16,
    i32,
    i64,
    i128
);

/// Allow `Cow<'a, str>` to be converted into a `Caveat`.
impl IntoCaveat for Cow<'_, str> {
    fn into_caveat<K: Kind>(self, warnings: Set<K>) -> Caveat<Self, K> {
        Caveat::new(self, warnings)
    }
}

/// Allow `Option<T: IntoCaveat>` to be converted into a `Caveat`.
impl<T> IntoCaveat for Option<T>
where
    T: IntoCaveat,
{
    fn into_caveat<K: Kind>(self, warnings: Set<K>) -> Caveat<Self, K> {
        Caveat::new(self, warnings)
    }
}

/// `Verdict` specific extinsion methods for the `Result` type.
pub trait VerdictExt<T, K: Kind> {
    /// Converts from `Verdict<T, K>` to `Caveat<Option<T>, K>`.
    ///
    /// The `Ok` and `Err` variants are encoded as `Some(T)` and `None` respectively and the [`Warning`]s are retained.
    fn ok_caveat(self) -> Caveat<Option<T>, K>;
}

impl<T, K: Kind> VerdictExt<T, K> for Verdict<T, K>
where
    T: IntoCaveat,
{
    fn ok_caveat(self) -> Caveat<Option<T>, K> {
        match self {
            Ok(v) => {
                let (v, warnings) = v.into_parts();
                Some(v).into_caveat(warnings)
            }
            Err(warnings) => None.into_caveat(warnings),
        }
    }
}

/// Implement a conversion from `warning::Set<A>` to `warning::Set<B>` so that the `Err` variant
/// of a `Verdict<_, A>` can be converted using the `?` operator to `Verdict<_, B>`.
///
/// `warning::Set::into_set` is used to perform the conversion between set A and B.
#[macro_export]
#[doc(hidden)]
macro_rules! from_warning_set_to {
    ($kind_a:path => $kind_b:path) => {
        impl From<$crate::warning::Set<$kind_a>> for $crate::warning::Set<$kind_b> {
            fn from(set_a: warning::Set<$kind_a>) -> Self {
                set_a.into_set()
            }
        }
    };
}

/// Convert an `Option` into a `Verdict` ready to exit the fn.
pub trait OptionExt<T, K>
where
    K: Kind,
{
    /// Convert an `Option` into a `Verdict` ready to exit the fn.
    fn exit_with_warning<F>(self, warnings: Set<K>, f: F) -> Verdict<T, K>
    where
        F: FnOnce() -> Warning<K>;
}

impl<T, K> OptionExt<T, K> for Option<T>
where
    T: IntoCaveat,
    K: Kind,
{
    fn exit_with_warning<F>(self, mut warnings: Set<K>, f: F) -> Verdict<T, K>
    where
        F: FnOnce() -> Warning<K>,
    {
        if let Some(v) = self {
            Ok(v.into_caveat(warnings))
        } else {
            warnings.push(f());
            Err(warnings)
        }
    }
}

/// Groups together a module's `Kind` and the associated [`json::Element`].
///
/// The [`json::Element`] is referenced by `ElemId`.
#[derive(Debug)]
pub struct Warning<K: Kind> {
    /// The kind of warning.
    kind: K,

    /// The Id of the element that caused the [`Warning`].
    elem_id: Option<json::ElemId>,
}

impl<K: Kind> Warning<K> {
    /// Create a Warning from a kind defined in a domain module and as associated `json::Element`.
    pub(crate) const fn with_elem(kind: K, elem: &json::Element<'_>) -> Warning<K> {
        Warning {
            kind,
            elem_id: Some(elem.id()),
        }
    }

    /// Create a Warning from a kind defined in a domain module.
    pub(crate) const fn only_kind(kind: K) -> Warning<K> {
        Warning {
            kind,
            elem_id: None,
        }
    }

    pub fn id(&self) -> Cow<'static, str> {
        self.kind.id()
    }

    pub fn kind(&self) -> &K {
        &self.kind
    }

    /// Consume the Warning and return the Kind of Warning.
    pub fn into_kind(self) -> K {
        self.kind
    }
}

impl<K: Kind> fmt::Display for Warning<K> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.kind)
    }
}

/// Each mod defines warnings for the type that it's trying to parse or lint from a [`json::Element`].
///
/// The `mod::Kind` should impl this trait to take part in the [`Warning`] system.
pub trait Kind: Sized + fmt::Debug + fmt::Display {
    /// Return the human readable identifier for the [`Warning`].
    ///
    /// This is used in the `auto_test` assertion system.
    /// Changing these strings may require updating `output_price__cdr.json` files.
    fn id(&self) -> Cow<'static, str>;
}

/// A set of [`Warning`]s transported through the system using a `Verdict` or `Caveat`.
#[derive(Debug)]
pub struct Set<K: Kind>(Vec<Warning<K>>);

impl<K: Kind> Set<K> {
    /// Create a new list of [`Warning`]s
    pub(crate) fn new() -> Self {
        Self(vec![])
    }

    /// Push a new [`Warning`] onto the list.
    fn push(&mut self, warning: Warning<K>) {
        self.0.push(warning);
    }

    /// Create and push a Warning from a kind defined in a domain module and as associated `json::Element`.
    pub(crate) fn with_elem(&mut self, kind: K, elem: &json::Element<'_>) {
        self.push(Warning::with_elem(kind, elem));
    }

    /// Create and push a Warning from a kind defined in a domain module.
    pub(crate) fn only_kind(&mut self, kind: K) {
        self.push(Warning::only_kind(kind));
    }

    /// Converts `Set<K>` into `Set<KB>` using the `impl From<K> for KB`.
    ///
    /// This is used by the `from_warning_set_to` macro.
    pub(crate) fn into_set<KB>(self) -> Set<KB>
    where
        KB: Kind + From<K>,
    {
        let warnings = self
            .0
            .into_iter()
            .map(|warn| {
                let Warning { kind, elem_id } = warn;
                Warning {
                    kind: kind.into(),
                    elem_id,
                }
            })
            .collect();

        Set(warnings)
    }

    /// Return the inner kinds.
    ///
    /// This should only be used in tests and the `mod price`.
    pub(crate) fn into_kind_vec(self) -> Vec<K> {
        self.0.into_iter().map(Warning::into_kind).collect()
    }

    /// Return the inner kinds.
    ///
    /// This should only be used in tests and the `mod price`.
    pub(crate) fn to_kind_vec(&self) -> Vec<&K> {
        self.0.iter().map(Warning::kind).collect()
    }

    /// Return true if the [`Warning`] list is empty.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Return true if the [`Warning`] list is empty.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Convert the set of [`Warning`]s into a `Report` ready for presentation.
    pub fn into_report(self) -> Report<K> {
        Report::new(self)
    }
}

/// A collection of [`Warning`]s grouped by [`json::Element`].
///
/// Use the `Report::iter` to iterate over the [`json::Element`]s that have [`Warning`]s in order.
#[derive(Debug)]
pub struct Report<K>
where
    K: Kind,
{
    groups: Vec<Group<K>>,
}

/// A `Group` of `WarningKind`s that all share the same `ElemeId`.
#[derive(Debug)]
struct Group<K> {
    /// The `ElemId` all [`Warning`]s share.
    id: Option<json::ElemId>,

    /// The group of `WarningKind`s.
    warning_kinds: Vec<K>,
}

impl<K> Report<K>
where
    K: Kind,
{
    /// Create a new `Report` ready to present each [`json::Element`] that has [`Warning`]s.
    fn new(warnings: Set<K>) -> Self {
        let Set(mut warnings) = warnings;
        // sort the warnings list so that we know the warngs are grouped by `ElemId`.
        warnings.sort_unstable_by(|a, b| a.elem_id.cmp(&b.elem_id));
        let mut warnings = warnings.into_iter();

        let Some(first) = warnings.next() else {
            return Self { groups: vec![] };
        };

        // Insert the first warning into the resulting elements list.
        // This is used as the first id to start grouping by.
        let mut groups = vec![Group {
            id: first.elem_id,
            warning_kinds: vec![first.kind],
        }];

        // Group the warnings by `ElemId`, the warnings list is already compacted so that the warnings
        // Are sorted by `ElemId`. This loop simplify cuts the [`Warning`] list up into those groups.
        for warn in warnings {
            // Compare the current [`Warning`] with the next to detect the end of the current run/group.
            if let Some(s) = groups.last_mut() {
                if warn.elem_id == s.id {
                    // The run continues, add the current `WarningKind` to the `Group`.
                    s.warning_kinds.push(warn.kind);
                } else {
                    // This is the end of the run/group. Create a new `Group`.
                    groups.push(Group {
                        id: warn.elem_id,
                        warning_kinds: vec![warn.kind],
                    });
                }
            }
        }

        Self { groups }
    }

    /// Iterate over all [`json::Element`]s that have [`Warning`]s.
    ///
    /// The iteration happens in the order of the `Element::id`
    pub fn iter<'a, 'bin>(&'a self, root: &'a json::Element<'bin>) -> ReportIter<'a, 'bin, K> {
        ReportIter {
            walker: json::walk::DepthFirst::new(root),
            groups: self.groups.iter(),
        }
    }

    /// Return true if there are no [`json::Element`]s with [`Warning`]s.
    pub fn is_empty(&self) -> bool {
        self.groups.is_empty()
    }

    /// Return the number of [`json::Element`]s with [`Warning`]s.
    pub fn len(&self) -> usize {
        self.groups.len()
    }
}

/// An iterator the walks over all [`json::Element`]s and returns `Some` if the given
/// [`json::Element`] has any [`Warning`]s.
pub struct ReportIter<'a, 'bin, K: Kind> {
    /// The [`json::Element`] tree walker.
    walker: json::walk::DepthFirst<'a, 'bin>,

    /// The iterator for all [`Warning`] `Group`s.
    groups: slice::Iter<'a, Group<K>>,
}

impl<'a, 'bin, K: Kind> Iterator for ReportIter<'a, 'bin, K> {
    type Item = ElementReport<'a, 'bin, K>;

    fn next(&mut self) -> Option<Self::Item> {
        let group = self.groups.next()?;

        // Resolve the [`Warning`] `Group`'s `ElemId` to an [`json::Element`] in the given tree.
        loop {
            let Some(element) = self.walker.next() else {
                if let Some(id) = group.id {
                    error!("An Element with id: `{id}` was not found");
                } else {
                    error!("An Element without an id was not found");
                }
                return None;
            };

            if let Some(id) = group.id {
                if element.id() == id {
                    return Some(ElementReport {
                        element,
                        warnings: &group.warning_kinds,
                    });
                }
            }
        }
    }
}

/// A report of all warnings for a given [`json::Element`].
pub struct ElementReport<'a, 'bin, K: Kind> {
    /// The [`json::Element`] that has [`Warning`]s.
    pub element: &'a json::Element<'bin>,

    /// The list of warnings for the [`json::Element`].
    pub warnings: &'a [K],
}

impl<K: Kind> fmt::Debug for ElementReport<'_, '_, K> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ElementReport")
            .field("element", &self.element.path())
            .field("warnings", &self.warnings)
            .finish()
    }
}

#[cfg(test)]
mod test {
    use std::{ops, slice};

    use assert_matches::assert_matches;

    use crate::json;

    use super::{Caveat, Kind, Set, Warning};
    impl<K: Kind> Warning<K> {
        pub(crate) fn elem_id(&self) -> Option<json::ElemId> {
            self.elem_id
        }
    }

    impl<K: Kind> Set<K> {
        /// Return the inner storage.
        pub fn into_vec(self) -> Vec<Warning<K>> {
            self.0
        }

        /// Return the inner kind and `json::ElemId`.
        pub(crate) fn into_parts_vec(self) -> Vec<(K, Option<json::ElemId>)> {
            self.0
                .into_iter()
                .map(|Warning { kind, elem_id }| (kind, elem_id))
                .collect()
        }

        /// Return the inner storgae as a slice.
        pub fn as_slice(&self) -> &[Warning<K>] {
            self.0.as_slice()
        }

        /// Return an immutable iterator over the slice.
        pub fn iter(&self) -> slice::Iter<'_, Warning<K>> {
            self.0.iter()
        }
    }

    impl<K: Kind> ops::Deref for Set<K> {
        type Target = [Warning<K>];

        fn deref(&self) -> &[Warning<K>] {
            self.as_slice()
        }
    }

    impl<K: Kind> IntoIterator for Set<K> {
        type Item = Warning<K>;

        type IntoIter = <Vec<Self::Item> as IntoIterator>::IntoIter;

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

    impl<'a, K: Kind> IntoIterator for &'a Set<K> {
        type Item = &'a Warning<K>;

        type IntoIter = slice::Iter<'a, Warning<K>>;

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

    impl<T, K> Caveat<T, K>
    where
        K: Kind,
    {
        /// Return the value and assert there are no [`Warning`]s.
        pub fn unwrap(self) -> T {
            let Self { value, warnings } = self;
            assert_matches!(warnings.into_vec().as_slice(), []);
            value
        }
    }
}

#[cfg(test)]
mod test_report {
    use std::fmt;

    use assert_matches::assert_matches;

    use crate::{json, test, warning::ElementReport};

    use super::{Kind, Report, Set, Warning};

    #[derive(Debug)]
    enum WarningKind {
        Root,
        One,
        OneAgain,
        Three,
    }

    impl Kind for WarningKind {
        fn id(&self) -> std::borrow::Cow<'static, str> {
            match self {
                WarningKind::Root => "root".into(),
                WarningKind::One => "one".into(),
                WarningKind::OneAgain => "one_again".into(),
                WarningKind::Three => "three".into(),
            }
        }
    }

    impl fmt::Display for WarningKind {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            match self {
                WarningKind::Root => write!(f, "NopeRoot"),
                WarningKind::One => write!(f, "NopeOne"),
                WarningKind::OneAgain => write!(f, "NopeOneAgain"),
                WarningKind::Three => write!(f, "NopeThree"),
            }
        }
    }

    #[test]
    fn should_group_warnings() {
        const JSON: &str = r#"{
    "field_one#": "one",
    "field_two": "two",
    "field_three": "three"
}"#;

        test::setup();

        let elem = parse(JSON);
        let mut warnings = Set::<WarningKind>::new();

        // Push warnings into the set out of order.
        // They should be sorted by `ElemId`.
        warnings.push(Warning {
            kind: WarningKind::Root,
            elem_id: Some(Into::into(0)),
        });
        warnings.push(Warning {
            kind: WarningKind::Three,
            elem_id: Some(Into::into(3)),
        });
        warnings.push(Warning {
            kind: WarningKind::One,
            elem_id: Some(Into::into(1)),
        });
        warnings.push(Warning {
            kind: WarningKind::OneAgain,
            elem_id: Some(Into::into(1)),
        });

        let report = Report::new(warnings);
        let mut iter = report.iter(&elem);
        let ElementReport { element, warnings } = iter.next().unwrap();

        assert!(
            element.value().is_object(),
            "The root object should be reported first"
        );
        assert_eq!(
            element.id(),
            json::ElemId::from(0),
            "The root object should be reported first"
        );
        assert_matches!(warnings, [WarningKind::Root]);

        let ElementReport { element, warnings } = iter.next().unwrap();

        assert_eq!(element.value().as_raw_str().unwrap().as_raw(), "one");
        assert_eq!(element.id(), json::ElemId::from(1));
        assert_matches!(
            warnings,
            [WarningKind::One, WarningKind::OneAgain],
            "[`json::Element`] 1 should have two warnings"
        );

        // [`json::Element`] 2 has no [`Warning`]s so we expect [`json::Element`] 3 next
        let ElementReport { element, warnings } = iter.next().unwrap();

        assert_eq!(element.value().as_raw_str().unwrap().as_raw(), "three");
        assert_eq!(element.id(), json::ElemId::from(3));
        assert_matches!(warnings, [WarningKind::Three]);
    }

    fn parse(json: &str) -> json::Element<'_> {
        json::parse(json).unwrap()
    }
}