1use crate::error::{HostSizeField, ParseLimitKind, ParserError, Result};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub struct ParseLimits {
22 pub max_kv_count: u64,
24 pub max_tensor_count: u64,
26 pub max_string_bytes: u64,
28 pub max_array_work_items: u64,
30 pub max_tensor_rank: u64,
32 pub max_metadata_bytes: u64,
34}
35
36impl ParseLimits {
37 pub const DEFAULT: Self = Self {
39 max_kv_count: 1_000_000,
40 max_tensor_count: 1_000_000,
41 max_string_bytes: 16 * 1024 * 1024,
42 max_array_work_items: 16_000_000,
43 max_tensor_rank: 8,
44 max_metadata_bytes: 256 * 1024 * 1024,
45 };
46
47 pub const TRUSTED: Self = Self {
50 max_kv_count: u64::MAX,
51 max_tensor_count: u64::MAX,
52 max_string_bytes: u64::MAX,
53 max_array_work_items: u64::MAX,
54 max_tensor_rank: u64::MAX,
55 max_metadata_bytes: u64::MAX,
56 };
57
58 pub const fn trusted() -> Self {
60 Self::TRUSTED
61 }
62
63 pub const fn budget(self, kind: ParseLimitKind) -> u64 {
65 match kind {
66 ParseLimitKind::KvCount => self.max_kv_count,
67 ParseLimitKind::TensorCount => self.max_tensor_count,
68 ParseLimitKind::StringBytes => self.max_string_bytes,
69 ParseLimitKind::ArrayWorkItems => self.max_array_work_items,
70 ParseLimitKind::TensorRank => self.max_tensor_rank,
71 ParseLimitKind::MetadataBytes => self.max_metadata_bytes,
72 }
73 }
74
75 pub(crate) fn reject(self, path: &str, kind: ParseLimitKind, declared: u64) -> Result<()> {
77 let budget = self.budget(kind);
78 if declared > budget {
79 Err(ParserError::limit_exceeded(path, kind, declared, budget))
80 } else {
81 Ok(())
82 }
83 }
84
85 pub(crate) fn bounded_usize(
87 self,
88 path: &str,
89 kind: ParseLimitKind,
90 field: HostSizeField,
91 declared: u64,
92 ) -> Result<usize> {
93 self.reject(path, kind, declared)?;
94 u64_to_usize(declared, field, path)
95 }
96}
97
98impl Default for ParseLimits {
99 fn default() -> Self {
100 Self::DEFAULT
101 }
102}
103
104pub(crate) fn u64_to_usize(value: u64, field: HostSizeField, path: &str) -> Result<usize> {
106 usize::try_from(value).map_err(|_| ParserError::host_size(path, field, value))
107}
108
109pub(crate) fn align_up_checked(value: usize, alignment: usize, path: &str) -> Result<usize> {
111 if alignment <= 1 {
112 return Ok(value);
113 }
114 let padding = alignment - 1;
115 let padded = value
116 .checked_add(padding)
117 .ok_or_else(|| ParserError::InvalidLayout {
118 path: path.to_owned(),
119 reason: "aligned tensor data offset overflow".into(),
120 })?;
121 Ok(padded - (padded % alignment))
122}
123
124#[cfg(test)]
125mod tests {
126 use super::*;
127
128 #[test]
129 fn default_limits_are_generous_and_named() {
130 let limits = ParseLimits::default();
131 assert_eq!(limits, ParseLimits::DEFAULT);
132 assert!(limits.max_kv_count >= 1_000_000);
133 assert!(limits.max_tensor_count >= 1_000_000);
134 assert!(limits.max_string_bytes >= 1024);
135 assert!(limits.max_array_work_items >= 32);
136 assert!(limits.max_tensor_rank >= 8);
137 assert!(limits.max_metadata_bytes >= 1024);
138 }
139
140 #[test]
141 fn trusted_does_not_change_default() {
142 assert_ne!(ParseLimits::trusted(), ParseLimits::default());
143 assert_eq!(ParseLimits::trusted().max_kv_count, u64::MAX);
144 assert_eq!(ParseLimits::default().max_kv_count, 1_000_000);
145 }
146
147 #[test]
148 fn reject_is_inclusive_at_the_budget() {
149 let limits = ParseLimits {
150 max_kv_count: 4,
151 ..ParseLimits::default()
152 };
153 limits
154 .reject("mem://lim", ParseLimitKind::KvCount, 4)
155 .expect("exact budget must pass");
156 let err = limits
157 .reject("mem://lim", ParseLimitKind::KvCount, 5)
158 .unwrap_err();
159 match err {
160 ParserError::LimitExceeded {
161 limit,
162 declared,
163 budget,
164 ..
165 } => {
166 assert_eq!(limit, ParseLimitKind::KvCount);
167 assert_eq!(declared, 5);
168 assert_eq!(budget, 4);
169 }
170 other => panic!("expected LimitExceeded, got {other}"),
171 }
172 }
173
174 #[test]
175 fn u64_to_usize_reports_field_when_unrepresentable() {
176 #[cfg(target_pointer_width = "32")]
177 {
178 let err = u64_to_usize(u64::MAX, HostSizeField::StringLen, "mem://host").unwrap_err();
179 match err {
180 ParserError::HostSizeOverflow { field, value, .. } => {
181 assert_eq!(field, HostSizeField::StringLen);
182 assert_eq!(value, u64::MAX);
183 }
184 other => panic!("expected HostSizeOverflow, got {other}"),
185 }
186 }
187 #[cfg(not(target_pointer_width = "32"))]
188 {
189 assert_eq!(
190 u64_to_usize(u64::MAX, HostSizeField::StringLen, "mem://host").unwrap(),
191 usize::MAX
192 );
193 }
194 }
195
196 #[test]
197 fn align_up_checked_rejects_overflow() {
198 let err = align_up_checked(usize::MAX, 32, "mem://align").unwrap_err();
199 let msg = err.to_string();
200 assert!(
201 msg.contains("aligned tensor data offset overflow"),
202 "got: {msg}"
203 );
204 }
205
206 #[test]
207 fn align_up_checked_rounds_up() {
208 assert_eq!(align_up_checked(1, 32, "mem://align").unwrap(), 32);
209 assert_eq!(align_up_checked(32, 32, "mem://align").unwrap(), 32);
210 assert_eq!(align_up_checked(7, 1, "mem://align").unwrap(), 7);
211 }
212}