Skip to main content

unityrs_core/value/
edit.rs

1//! Scalar edits retain the parsed allocation and any charged byte owners.
2use super::{Parsed, Value, builder::owns_heap};
3use crate::limits::ChargeError;
4
5impl Parsed {
6    /// Replace an existing field without allocating. Strings and bytes must
7    /// own charged storage, as for `ValueBuilder::scalar`. Heap containers
8    /// are refused; their charges cannot be transferred through this API.
9    /// Missing paths and containers return false, leaving the value intact.
10    pub fn replace_scalar(&mut self, path: &[&[u8]], value: Value) -> Result<bool, ChargeError> {
11        if owns_heap(&value) || path.is_empty() {
12            return Ok(false);
13        }
14        let mut current = &mut self.value;
15        for name in path {
16            let Value::Dict(map) = current else {
17                return Ok(false);
18            };
19            let Some(list) = self.lists.get(map.list as usize) else {
20                return Ok(false);
21            };
22            let mut found = None;
23            for (key, child) in &mut map.entries {
24                let key_name = list.name(*key);
25                self.charge
26                    .meter()
27                    .count_decode(1 + key_name.len().min(name.len()) as u64)?;
28                if key_name == *name {
29                    found = Some(child);
30                    break;
31                }
32            }
33            let Some(child) = found else { return Ok(false) };
34            current = child;
35        }
36        *current = value;
37        Ok(true)
38    }
39}