use core::num::NonZeroU64;
use airsl::{InstructionLimit, MemoryLimit, ResourceLimits};
const DEFAULT_MEMORY_BYTES: NonZeroU64 = NonZeroU64::MIN.saturating_add(16 * 1024 * 1024 - 1);
const DEFAULT_INSTRUCTIONS: NonZeroU64 = NonZeroU64::MIN.saturating_add(10_000_000 - 1);
const DEFAULT_WALK_ENTRIES: NonZeroU64 = NonZeroU64::MIN.saturating_add(100_000 - 1);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DeclarationLimits {
memory_bytes: NonZeroU64,
instructions: NonZeroU64,
walk_entries: NonZeroU64,
}
impl DeclarationLimits {
#[must_use]
pub const fn new(memory_bytes: NonZeroU64, instructions: NonZeroU64) -> Self {
Self {
memory_bytes,
instructions,
walk_entries: DEFAULT_WALK_ENTRIES,
}
}
#[must_use]
pub const fn with_walk_entries(self, walk_entries: NonZeroU64) -> Self {
Self {
walk_entries,
..self
}
}
#[must_use]
pub const fn walk_entries(&self) -> NonZeroU64 {
self.walk_entries
}
#[must_use]
pub const fn memory_bytes(&self) -> NonZeroU64 {
self.memory_bytes
}
#[must_use]
pub const fn instructions(&self) -> NonZeroU64 {
self.instructions
}
pub(crate) fn resource_limits(&self) -> ResourceLimits {
let memory = usize::try_from(self.memory_bytes.get()).unwrap_or(usize::MAX);
ResourceLimits::new(
Some(MemoryLimit::bytes(memory)),
Some(InstructionLimit::count(self.instructions.get())),
)
}
}
impl Default for DeclarationLimits {
fn default() -> Self {
Self::new(DEFAULT_MEMORY_BYTES, DEFAULT_INSTRUCTIONS)
}
}
#[cfg(test)]
mod tests {
use core::num::NonZeroU64;
use airsl::{InstructionLimit, MemoryLimit};
use super::DeclarationLimits;
#[test]
fn defaults_to_sixteen_mebibytes_ten_million_instructions_and_a_hundred_thousand_entries() {
let limits = DeclarationLimits::default();
assert_eq!(limits.memory_bytes().get(), 16_777_216);
assert_eq!(limits.instructions().get(), 10_000_000);
assert_eq!(limits.walk_entries().get(), 100_000);
}
#[test]
fn new_takes_the_default_walk_ceiling_and_with_walk_entries_replaces_only_it() {
let two = NonZeroU64::MIN.saturating_add(1);
let limits = DeclarationLimits::new(two, two);
assert_eq!(limits.walk_entries().get(), 100_000);
let walked = limits.with_walk_entries(NonZeroU64::MIN);
assert_eq!(walked.walk_entries().get(), 1);
assert_eq!(walked.memory_bytes(), two);
assert_eq!(walked.instructions(), two);
}
#[test]
fn converts_into_both_airsl_ceilings() {
let limits = DeclarationLimits::new(NonZeroU64::MIN, NonZeroU64::MIN.saturating_add(1));
let resource = limits.resource_limits();
assert_eq!(resource.memory(), Some(MemoryLimit::bytes(1)));
assert_eq!(resource.instructions(), Some(InstructionLimit::count(2)));
}
}