use std::fmt;
pub const DEFAULT_MAX_DEPTH: u32 = 256;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LimitExceeded {
Depth {
max: u32,
line: u32,
column: u32,
},
Nesting {
max: u32,
},
Stack {
max: u32,
},
TailCalls {
max: u32,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StackLimit {
base: usize,
max: u32,
}
impl StackLimit {
#[must_use]
#[inline(never)]
pub fn from_here(max: u32) -> Self {
Self {
base: stack_position(),
max,
}
}
#[must_use]
pub const fn max(self) -> u32 {
self.max
}
#[must_use]
pub fn used(self) -> usize {
self.base.abs_diff(stack_position())
}
pub fn check(self) -> Result<(), LimitExceeded> {
if u32::try_from(self.used()).map_or(true, |used| used > self.max) {
Err(LimitExceeded::Stack { max: self.max })
} else {
Ok(())
}
}
}
#[inline(never)]
fn stack_position() -> usize {
let marker = 0_u8;
std::hint::black_box(std::ptr::addr_of!(marker)).addr()
}
impl LimitExceeded {
#[must_use]
pub const fn max(self) -> u32 {
match self {
Self::Depth { max, .. }
| Self::Nesting { max }
| Self::Stack { max }
| Self::TailCalls { max } => max,
}
}
}
impl fmt::Display for LimitExceeded {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Depth { max, line, column } => write!(
f,
"{line}:{column}: element nested deeper than the maximum depth of {max}"
),
Self::Nesting { max } => write!(
f,
"templates and functions invoked one inside another more than {max} deep"
),
Self::Stack { max } => write!(
f,
"templates and functions invoked one inside another use more than {max} bytes of stack"
),
Self::TailCalls { max } => write!(
f,
"templates ending with a call of another template more than {max} times in a row"
),
}
}
}