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
//! Overflow-safe utilities for tracking JSON document depth.
use super::error::DepthError;
use std::{
    fmt::Display,
    ops::{Add, Deref, Sub},
};

/// Overflow-safe thin wrapper for a [`u8`] depth counter.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Depth(u8);

impl Depth {
    /// Depth of 0.
    pub const ZERO: Self = Self(0);

    /// Depth of 1.
    pub const ONE: Self = Self(1);

    /// Add `1` to the depth, or raise an error if the maximum
    /// supported value is reached.
    pub fn increment(&mut self) -> Result<(), DepthError> {
        *self = (*self + 1)?;
        Ok(())
    }

    /// Subtract `1` from the depth, or raise an error if the depth
    /// is zero.
    pub fn decrement(&mut self) -> Result<(), DepthError> {
        *self = (*self - 1)?;
        Ok(())
    }
}

macro_rules! impl_add {
    ($t:ty) => {
        impl Add<u8> for $t {
            type Output = Result<Depth, DepthError>;

            #[inline]
            fn add(self, rhs: u8) -> Self::Output {
                self.0
                    .checked_add(rhs)
                    .ok_or(DepthError::AboveLimit(u8::MAX as usize))
                    .map(Depth)
            }
        }
    };
}

macro_rules! impl_sub {
    ($t:ty) => {
        impl Sub<u8> for $t {
            type Output = Result<Depth, DepthError>;

            #[inline]
            fn sub(self, rhs: u8) -> Self::Output {
                self.0.checked_sub(rhs).ok_or(DepthError::BelowZero).map(Depth)
            }
        }
    };
}

impl_add!(Depth);
impl_add!(&Depth);
impl_add!(&mut Depth);

impl_sub!(Depth);
impl_sub!(&Depth);
impl_sub!(&mut Depth);

impl Display for Depth {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl Deref for Depth {
    type Target = u8;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}