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
//! Overflow-safe utilities for tracking JSON document depth.

use super::error::EngineError;
use std::{fmt::Display, ops::Deref};

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

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

    /// Add `1` to the depth, or raise an error if the maximum
    /// supported value is reached.
    pub(crate) fn increment(&mut self) -> Result<(), EngineError> {
        self.value = self
            .value
            .checked_add(1)
            .ok_or(EngineError::DepthAboveLimit(u8::MAX as usize))?;
        Ok(())
    }

    /// Subtract `1` from the depth, or raise an error if the depth
    /// is zero.
    pub(crate) fn decrement(&mut self) -> Result<(), EngineError> {
        self.value = self
            .value
            .checked_sub(1)
            .ok_or(EngineError::DepthBelowZero)?;
        Ok(())
    }
}

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

impl Deref for Depth {
    type Target = u8;

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