Skip to main content

jsonld_core/
warning.rs

1use contextual::{DisplayWithContext, WithContext};
2
3/// Warning handler.
4///
5/// This trait is implemented by the unit type `()` which ignores warnings.
6/// You can use [`Print`] or [`PrintWith`] to print warnings on the standard
7/// output or implement your own handler.
8pub trait Handler<N, W> {
9    /// Handle a warning with the given `vocabulary`.
10    fn handle(&mut self, vocabulary: &N, warning: W);
11}
12
13impl<N, W> Handler<N, W> for () {
14    fn handle(&mut self, _vocabulary: &N, _warning: W) {}
15}
16
17impl<N, W, H: Handler<N, W>> Handler<N, W> for &mut H {
18    fn handle(&mut self, vocabulary: &N, warning: W) {
19        H::handle(*self, vocabulary, warning);
20    }
21}
22
23/// Prints warnings that can be displayed without vocabulary on the standard
24/// output.
25pub struct Print;
26
27impl<N, W: std::fmt::Display> Handler<N, W> for Print {
28    fn handle(&mut self, _vocabulary: &N, warning: W) {
29        eprintln!("{warning}");
30    }
31}
32
33/// Prints warnings with a given vocabulary on the standard output.
34pub struct PrintWith;
35
36impl<N, W: DisplayWithContext<N>> Handler<N, W> for PrintWith {
37    fn handle(&mut self, vocabulary: &N, warning: W) {
38        eprintln!("{}", warning.with(vocabulary));
39    }
40}
41
42/// Warning handler that collects warnings into a [`Vec`] rather than
43/// reporting them as they are raised.
44///
45/// Use it when warnings need to be inspected, filtered or reordered after
46/// the algorithm has finished.
47pub struct WarningBuf<W>(pub Vec<W>);
48
49impl<W> Default for WarningBuf<W> {
50    fn default() -> Self {
51        Self(Vec::new())
52    }
53}
54
55impl<W> WarningBuf<W> {
56    /// Creates a new `WarningBuf`.
57    #[must_use]
58    pub fn new() -> Self {
59        Self::default()
60    }
61}
62
63impl<N, W> Handler<N, W> for WarningBuf<W> {
64    fn handle(&mut self, _vocabulary: &N, warning: W) {
65        self.0.push(warning);
66    }
67}