1use core::num::NonZeroU64;
12
13use airsl::{InstructionLimit, MemoryLimit, ResourceLimits};
14
15const DEFAULT_MEMORY_BYTES: NonZeroU64 = NonZeroU64::MIN.saturating_add(16 * 1024 * 1024 - 1);
17const DEFAULT_INSTRUCTIONS: NonZeroU64 = NonZeroU64::MIN.saturating_add(10_000_000 - 1);
19
20const DEFAULT_WALK_ENTRIES: NonZeroU64 = NonZeroU64::MIN.saturating_add(100_000 - 1);
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct DeclarationLimits {
48 memory_bytes: NonZeroU64,
49 instructions: NonZeroU64,
50 walk_entries: NonZeroU64,
51}
52
53impl DeclarationLimits {
54 #[must_use]
57 pub const fn new(memory_bytes: NonZeroU64, instructions: NonZeroU64) -> Self {
58 Self {
59 memory_bytes,
60 instructions,
61 walk_entries: DEFAULT_WALK_ENTRIES,
62 }
63 }
64
65 #[must_use]
67 pub const fn with_walk_entries(self, walk_entries: NonZeroU64) -> Self {
68 Self {
69 walk_entries,
70 ..self
71 }
72 }
73
74 #[must_use]
77 pub const fn walk_entries(&self) -> NonZeroU64 {
78 self.walk_entries
79 }
80
81 #[must_use]
83 pub const fn memory_bytes(&self) -> NonZeroU64 {
84 self.memory_bytes
85 }
86
87 #[must_use]
89 pub const fn instructions(&self) -> NonZeroU64 {
90 self.instructions
91 }
92
93 pub(crate) fn resource_limits(&self) -> ResourceLimits {
96 let memory = usize::try_from(self.memory_bytes.get()).unwrap_or(usize::MAX);
97 ResourceLimits::new(
98 Some(MemoryLimit::bytes(memory)),
99 Some(InstructionLimit::count(self.instructions.get())),
100 )
101 }
102}
103
104impl Default for DeclarationLimits {
105 fn default() -> Self {
107 Self::new(DEFAULT_MEMORY_BYTES, DEFAULT_INSTRUCTIONS)
108 }
109}
110
111#[cfg(test)]
112mod tests {
113 use core::num::NonZeroU64;
114
115 use airsl::{InstructionLimit, MemoryLimit};
116
117 use super::DeclarationLimits;
118
119 #[test]
120 fn defaults_to_sixteen_mebibytes_ten_million_instructions_and_a_hundred_thousand_entries() {
121 let limits = DeclarationLimits::default();
122 assert_eq!(limits.memory_bytes().get(), 16_777_216);
123 assert_eq!(limits.instructions().get(), 10_000_000);
124 assert_eq!(limits.walk_entries().get(), 100_000);
125 }
126
127 #[test]
128 fn new_takes_the_default_walk_ceiling_and_with_walk_entries_replaces_only_it() {
129 let two = NonZeroU64::MIN.saturating_add(1);
130 let limits = DeclarationLimits::new(two, two);
131 assert_eq!(limits.walk_entries().get(), 100_000);
132 let walked = limits.with_walk_entries(NonZeroU64::MIN);
133 assert_eq!(walked.walk_entries().get(), 1);
134 assert_eq!(walked.memory_bytes(), two);
135 assert_eq!(walked.instructions(), two);
136 }
137
138 #[test]
139 fn converts_into_both_airsl_ceilings() {
140 let limits = DeclarationLimits::new(NonZeroU64::MIN, NonZeroU64::MIN.saturating_add(1));
141 let resource = limits.resource_limits();
142 assert_eq!(resource.memory(), Some(MemoryLimit::bytes(1)));
143 assert_eq!(resource.instructions(), Some(InstructionLimit::count(2)));
144 }
145}