1use serde_json::{Map, Value};
19
20pub const MAX_ARRAY_INDEX: usize = 10_000;
22
23const FORBIDDEN: &[&str] = &["__proto__", "constructor", "prototype"];
24
25#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
27#[error("{message}")]
28pub struct DataError {
29 pub message: String,
31 pub path: String,
33}
34
35fn error(path: &str, message: String) -> DataError {
36 DataError {
37 message,
38 path: path.to_string(),
39 }
40}
41
42pub fn segments(path: &str) -> Result<Vec<String>, DataError> {
45 let mut out = Vec::new();
46 for raw in path.split('/').filter(|s| !s.is_empty()) {
47 let segment = raw.replace("~1", "/").replace("~0", "~");
48 if FORBIDDEN.contains(&segment.as_str()) {
49 return Err(error(
50 path,
51 format!("Forbidden path segment '{segment}' in path '{path}'."),
52 ));
53 }
54 out.push(segment);
55 }
56 Ok(out)
57}
58
59pub fn pointer(segments: &[String]) -> String {
61 if segments.is_empty() {
62 return "/".into();
63 }
64 segments
65 .iter()
66 .map(|s| format!("/{}", s.replace('~', "~0").replace('/', "~1")))
67 .collect()
68}
69
70pub fn normalize(path: &str) -> Result<String, DataError> {
73 Ok(pointer(&segments(path)?))
74}
75
76pub fn resolve(context: &str, path: &str) -> String {
80 if path.starts_with('/') {
81 return path.to_string();
82 }
83 let base = context.trim_end_matches('/');
84 if path.is_empty() || path == "." {
85 return if base.is_empty() {
86 "/".into()
87 } else {
88 base.to_string()
89 };
90 }
91 format!("{base}/{path}")
92}
93
94fn index(segment: &str) -> Option<usize> {
96 let canonical = !segment.is_empty()
97 && segment.bytes().all(|b| b.is_ascii_digit())
98 && (segment == "0" || !segment.starts_with('0'));
99 if canonical {
100 segment.parse().ok()
101 } else {
102 None
103 }
104}
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
108pub struct WatchId(usize);
109
110#[derive(Debug, Clone, PartialEq)]
112pub struct DataModel {
113 root: Value,
114 watches: Vec<(WatchId, Vec<String>)>,
115 next: usize,
116}
117
118impl Default for DataModel {
119 fn default() -> Self {
120 Self::new(Value::Object(Map::new()))
121 }
122}
123
124impl DataModel {
125 pub fn new(root: Value) -> Self {
127 Self {
128 root,
129 watches: Vec::new(),
130 next: 0,
131 }
132 }
133
134 pub fn root(&self) -> &Value {
136 &self.root
137 }
138
139 pub fn get(&self, path: &str) -> Result<Option<&Value>, DataError> {
141 Ok(lookup(&self.root, &segments(path)?))
142 }
143
144 pub fn watch(&mut self, path: &str) -> Result<WatchId, DataError> {
147 let id = WatchId(self.next);
148 self.next += 1;
149 self.watches.push((id, segments(path)?));
150 Ok(id)
151 }
152
153 pub fn dispose(&mut self) {
155 self.watches.clear();
156 }
157
158 pub fn set(&mut self, path: &str, value: Value) -> Result<Vec<WatchId>, DataError> {
161 let parts = segments(path)?;
162 let before = self.snapshot();
163 write(&mut self.root, &parts, path, Some(value))?;
164 Ok(self.changed(before))
165 }
166
167 pub fn delete(&mut self, path: &str) -> Result<Vec<WatchId>, DataError> {
170 let parts = segments(path)?;
171 let before = self.snapshot();
172 if parts.is_empty() {
173 self.root = Value::Object(Map::new());
174 } else if lookup_parent(&self.root, &parts).is_some() {
175 write(&mut self.root, &parts, path, None)?;
176 }
177 Ok(self.changed(before))
178 }
179
180 fn snapshot(&self) -> Vec<Option<Value>> {
181 self.watches
182 .iter()
183 .map(|(_, path)| lookup(&self.root, path).cloned())
184 .collect()
185 }
186
187 fn changed(&self, before: Vec<Option<Value>>) -> Vec<WatchId> {
188 self.watches
189 .iter()
190 .zip(before)
191 .filter(|((_, path), old)| lookup(&self.root, path) != old.as_ref())
192 .map(|((id, _), _)| *id)
193 .collect()
194 }
195}
196
197fn lookup<'a>(root: &'a Value, parts: &[String]) -> Option<&'a Value> {
198 let mut current = root;
199 for part in parts {
200 current = match current {
201 Value::Object(map) => map.get(part)?,
202 Value::Array(items) => items.get(index(part)?)?,
203 _ => return None,
204 };
205 }
206 (!current.is_null()).then_some(current)
207}
208
209fn lookup_parent<'a>(root: &'a Value, parts: &[String]) -> Option<&'a Value> {
211 let (_, parents) = parts.split_last()?;
212 let mut current = root;
213 for part in parents {
214 current = match current {
215 Value::Object(map) => map.get(part)?,
216 Value::Array(items) => items.get(index(part)?)?,
217 _ => return None,
218 };
219 }
220 matches!(current, Value::Object(_) | Value::Array(_)).then_some(current)
221}
222
223fn container_for(next: &str) -> Value {
224 if index(next).is_some() {
225 Value::Array(Vec::new())
226 } else {
227 Value::Object(Map::new())
228 }
229}
230
231fn write(
233 root: &mut Value,
234 parts: &[String],
235 path: &str,
236 value: Option<Value>,
237) -> Result<(), DataError> {
238 let Some((last, parents)) = parts.split_last() else {
239 root.clone_from(&value.unwrap_or_else(|| Value::Object(Map::new())));
240 return Ok(());
241 };
242 let primitive = |segment: &str| {
243 error(
244 path,
245 format!("Cannot set path '{path}': segment '{segment}' is a primitive value."),
246 )
247 };
248 if !matches!(root, Value::Object(_) | Value::Array(_) | Value::Null) {
249 return Err(error(
250 path,
251 format!("Cannot set path '{path}': the data model root is a primitive value."),
252 ));
253 }
254 if root.is_null() {
255 *root = container_for(&parts[0]);
256 }
257 let mut current = root;
258 for (position, part) in parents.iter().enumerate() {
259 let next = &parts[position + 1];
260 let slot = match current {
261 Value::Object(map) => map.entry(part.clone()).or_insert(Value::Null),
262 Value::Array(items) => {
263 let i = array_index(part, path)?;
264 if i >= items.len() {
265 items.resize(i + 1, Value::Null);
266 }
267 &mut items[i]
268 }
269 _ => return Err(primitive(part)),
270 };
271 if slot.is_null() {
272 if let Some(i) = index(next) {
273 if i > MAX_ARRAY_INDEX {
274 return Err(too_large(path, next));
275 }
276 }
277 *slot = container_for(next);
278 } else if !matches!(slot, Value::Object(_) | Value::Array(_)) {
279 return Err(primitive(next));
280 }
281 current = slot;
282 }
283 match current {
284 Value::Object(map) => match value {
285 Some(value) => {
286 map.insert(last.clone(), value);
287 }
288 None => {
289 map.remove(last);
290 }
291 },
292 Value::Array(items) => {
293 let i = array_index(last, path)?;
294 match value {
295 Some(value) => {
296 if i >= items.len() {
297 items.resize(i + 1, Value::Null);
298 }
299 items[i] = value;
300 }
301 None => {
302 if let Some(slot) = items.get_mut(i) {
303 *slot = Value::Null;
304 }
305 }
306 }
307 }
308 _ => return Err(primitive(last)),
309 }
310 Ok(())
311}
312
313fn array_index(segment: &str, path: &str) -> Result<usize, DataError> {
314 let Some(i) = index(segment) else {
315 return Err(error(
316 path,
317 format!("Cannot use non-numeric segment '{segment}' on an array in path '{path}'."),
318 ));
319 };
320 if i > MAX_ARRAY_INDEX {
321 return Err(too_large(path, segment));
322 }
323 Ok(i)
324}
325
326fn too_large(path: &str, segment: &str) -> DataError {
327 error(
328 path,
329 format!(
330 "Cannot set path '{path}': array index '{segment}' exceeds maximum supported index ({MAX_ARRAY_INDEX})."
331 ),
332 )
333}