Skip to main content

datex_core/values/value/
update_handler.rs

1use core::cell::RefCell;
2
3use crate::{
4    prelude::*,
5    runtime::cache::shared_references_cache::SharedReferencesCache,
6    shared_values::base_shared_value_container::observers::TransceiverId,
7    traits::local_child_path_resolver::LocalChildPathResolver,
8    value_updates::{
9        update_data::UpdateOperation,
10        update_handler::{
11            InternalMutabilityUpdateHandler, UpdateCallbackData,
12            UpdateCallbackDataAccess, UpdateHandlerImpl, UpdateResult,
13        },
14    },
15    values::{value::Value, value_container::ValueContainer},
16};
17
18impl InternalMutabilityUpdateHandler for Value {
19    fn set_update_callback_data(
20        &mut self,
21        observe_data: Option<UpdateCallbackData>,
22    ) {
23        match self {
24            Value::Core(core) => core.set_update_callback_data(observe_data),
25            Value::Native(_native) => {
26                // todo!()
27            }
28        }
29    }
30}
31
32impl UpdateCallbackDataAccess for Value {
33    fn get_update_callback_data(&self) -> Option<&UpdateCallbackData> {
34        match &self {
35            Value::Core(core) => core.get_update_callback_data(),
36            Value::Native(native) => native.get_update_callback_data(),
37        }
38    }
39}
40
41impl Value {
42    pub(crate) fn try_update_collapsed_local_inner(
43        &mut self,
44        operation: UpdateOperation,
45        path: Vec<ValueContainer>,
46        source_id: Option<TransceiverId>,
47        cache: &RefCell<SharedReferencesCache>,
48    ) -> UpdateResult {
49        // first collapse path to most inner nested value
50        let inner_local =
51            if let Some(([first], rest)) = path.split_at_checked(1) {
52                self.resolve_value_for_path(first, rest)?
53            } else {
54                self
55            };
56
57        // then apply update
58        inner_local.try_update(operation, source_id, cache)
59    }
60}
61
62impl UpdateHandlerImpl for Value {
63    /// Tries to update the value with the given operation.
64    /// If a path first needs to be resolved, use [Value::try_update_collapsed_local_inner]
65    fn try_update(
66        &mut self,
67        operation: UpdateOperation,
68        source_id: Option<TransceiverId>,
69        cache: &RefCell<SharedReferencesCache>,
70    ) -> UpdateResult {
71        match self {
72            Value::Core(core) => core.try_update(operation, source_id, cache),
73            Value::Native(native) => {
74                native.try_update(operation, source_id, cache)
75            }
76        }
77    }
78}
79
80#[cfg(test)]
81mod tests {
82    use crate::{
83        prelude::*,
84        runtime::cache::shared_references_cache::SharedReferencesCache,
85        shared_values::{
86            base_shared_value_container::observers::TransceiverId,
87            errors::{AccessError, IndexOutOfBoundsError},
88        },
89        value_updates::{
90            errors::UpdateError,
91            update_data::UpdateOperation,
92            update_handler::{
93                InternalMutabilityUpdateHandler, UpdateCallbackData,
94                UpdateCallbackDataAccess, UpdateHandlerImpl,
95            },
96        },
97        values::{
98            core_values::{list::List, map::Map},
99            value::Value,
100            value_container::ValueContainer,
101        },
102    };
103    use core::{assert_matches, cell::RefCell, ops::Deref};
104
105    #[test]
106    fn push() {
107        let cache = RefCell::new(SharedReferencesCache::default());
108        // Push to list value
109        let mut list = Value::from(List::from(vec![
110            ValueContainer::from(1),
111            ValueContainer::from(2),
112            ValueContainer::from(3),
113        ]));
114        list.try_update_collapsed_local_inner(
115            UpdateOperation::append_entry(ValueContainer::from(4)),
116            vec![],
117            None,
118            &cache,
119        )
120        .expect("Failed to push value to list");
121        let updated_value =
122            list.try_get_property(&ValueContainer::from(3u32)).unwrap();
123        assert_eq!(updated_value.try_as::<i32>().unwrap().deref(), &4);
124
125        // Try to push to non-list value
126        let mut int = Value::from(42);
127        let result = int.try_update_collapsed_local_inner(
128            UpdateOperation::append_entry(ValueContainer::from(4)),
129            vec![],
130            None,
131            &cache,
132        );
133        assert_matches!(result, Err(UpdateError::InvalidUpdate))
134    }
135
136    #[test]
137    fn get_set_property() {
138        let cache = RefCell::new(SharedReferencesCache::default());
139        let mut map = Value::from(Map::from(vec![
140            ("key1".to_string(), ValueContainer::from(1)),
141            ("key2".to_string(), ValueContainer::from(2)),
142        ]));
143
144        map.try_update_collapsed_local_inner(
145            UpdateOperation::set_entry("key1".into(), ValueContainer::from(42)),
146            vec![],
147            None,
148            &cache,
149        )
150        .expect("Failed to set existing property");
151        let updated_value =
152            map.try_get_property(&ValueContainer::from("key1")).unwrap();
153        assert_eq!(updated_value.try_as::<i32>().unwrap().deref(), &42);
154
155        // Set new property
156        let result = map.try_update_collapsed_local_inner(
157            UpdateOperation::set_entry("new".into(), ValueContainer::from(99)),
158            vec![],
159            None,
160            &cache,
161        );
162        assert!(result.is_ok());
163        let new_value =
164            map.try_get_property(&ValueContainer::from("new")).unwrap();
165        assert_eq!(new_value.try_as::<i32>().unwrap().deref(), &99);
166    }
167
168    #[test]
169    fn numeric_property() {
170        let mut list = Value::native(vec![
171            ValueContainer::from(1),
172            ValueContainer::from(2),
173            ValueContainer::from(3),
174        ]);
175
176        let cache = RefCell::new(SharedReferencesCache::default());
177        // Set existing index
178        list.try_update_collapsed_local_inner(
179            UpdateOperation::set_entry(1u32.into(), ValueContainer::from(42)),
180            vec![],
181            None,
182            &cache,
183        )
184        .expect("Failed to set existing index");
185        let updated_value =
186            list.try_get_property(&ValueContainer::from(1u32)).unwrap();
187        assert_eq!(updated_value.try_as::<i32>().unwrap().deref(), &42);
188
189        // Try to set out-of-bounds index
190        let result = list.try_update_collapsed_local_inner(
191            UpdateOperation::set_entry(5u32.into(), ValueContainer::from(99)),
192            vec![],
193            None,
194            &cache,
195        );
196        assert_eq!(
197            result,
198            Err(UpdateError::access_error(AccessError::IndexOutOfBounds(
199                IndexOutOfBoundsError { index: 5 }
200            )))
201        );
202
203        // Try to set index on non-map value
204        let mut int_ref = Value::from(1);
205        let result = int_ref.try_update_collapsed_local_inner(
206            UpdateOperation::set_entry(0u32.into(), ValueContainer::from(42)),
207            vec![],
208            None,
209            &cache,
210        );
211        assert_matches!(result, Err(UpdateError::InvalidUpdate));
212    }
213
214    #[test]
215    fn text_property() {
216        let cache = RefCell::new(SharedReferencesCache::default());
217        let mut struct_val = Value::from(Map::from(vec![
218            (ValueContainer::from("name"), ValueContainer::from("Alice")),
219            (ValueContainer::from("age"), ValueContainer::from(30)),
220        ]));
221
222        // Set existing property
223        struct_val
224            .try_update_collapsed_local_inner(
225                UpdateOperation::set_entry(
226                    "name".into(),
227                    ValueContainer::from("Bob".to_string()),
228                ),
229                vec![],
230                None,
231                &cache,
232            )
233            .expect("Failed to set existing property");
234        let name = struct_val
235            .try_get_property(&ValueContainer::from("name"))
236            .unwrap();
237        assert_eq!(name.try_as::<str>().unwrap().deref(), "Bob");
238
239        // Try to set non-existing property
240        let result = struct_val.try_update_collapsed_local_inner(
241            UpdateOperation::set_entry(
242                "non_existing".into(),
243                ValueContainer::from("Charlie".to_string()),
244            ),
245            vec![],
246            None,
247            &cache,
248        );
249        assert_matches!(result, Ok(_));
250
251        // // Try to set property on non-struct value
252        let mut int = Value::from(1);
253        let result = int.try_update_collapsed_local_inner(
254            UpdateOperation::set_entry(
255                "name".into(),
256                ValueContainer::from("Bob".to_string()),
257            ),
258            vec![],
259            None,
260            &cache,
261        );
262        assert_matches!(result, Err(UpdateError::InvalidUpdate));
263    }
264
265    #[test]
266    fn nested_map_property() {
267        let cache = RefCell::new(SharedReferencesCache::default());
268        let mut nested_map = Value::from(Map::from(vec![(
269            ValueContainer::from("outer".to_string()),
270            ValueContainer::from(Map::from(vec![(
271                ValueContainer::from("inner".to_string()),
272                ValueContainer::from(1),
273            )])),
274        )]));
275
276        // Set existing nested property
277        nested_map
278            .try_update_collapsed_local_inner(
279                UpdateOperation::set_entry(
280                    "inner".into(),
281                    ValueContainer::from(42),
282                ),
283                vec![ValueContainer::local("outer".to_string())],
284                None,
285                &cache,
286            )
287            .expect("Failed to set existing nested property");
288        let prop = nested_map
289            .try_get_property(&ValueContainer::from("outer"))
290            .unwrap();
291        let inner_value = prop.try_as::<Map>().unwrap();
292        let inner_value =
293            inner_value.try_get(&ValueContainer::from("inner")).unwrap();
294        assert_eq!(inner_value.try_as::<i32>().unwrap(), &42);
295    }
296
297    #[test]
298    fn observer_callbacks() {
299        let cache = RefCell::new(SharedReferencesCache::default());
300        let mut list = Value::from(List::from(vec![
301            ValueContainer::from(List::from(vec![1])),
302            ValueContainer::from(2),
303        ]));
304
305        let callback_updates = Rc::new(RefCell::new(vec![]));
306        let callback_updates_clone = callback_updates.clone();
307
308        list.set_update_callback_data(Some(UpdateCallbackData {
309            callback: Rc::new(move |update| {
310                callback_updates_clone.borrow_mut().push(update.clone());
311            }),
312            path: vec![],
313        }));
314
315        // Push to list value (should not trigger callback since source id is None)
316        list.try_update_collapsed_local_inner(
317            UpdateOperation::append_entry(ValueContainer::from(4)),
318            vec![],
319            None,
320            &cache,
321        )
322        .expect("Failed to push value to list");
323
324        // Push to list value (should trigger callback)
325        list.try_update_collapsed_local_inner(
326            UpdateOperation::append_entry(ValueContainer::from(5)),
327            vec![],
328            Some(TransceiverId::Local),
329            &cache,
330        )
331        .expect("Failed to push value to list");
332
333        // Check that the callback was triggered
334        {
335            let updates = callback_updates.borrow();
336            assert_eq!(updates.len(), 1);
337            assert_eq!(
338                updates[0].operation(),
339                &UpdateOperation::append_entry(ValueContainer::from(5))
340            );
341            assert_eq!(updates[0].path(), &vec![]);
342        }
343
344        {
345            // get inner list value and check that it has the correct update callback data
346            // (should be auto derived for children)
347            let inner = list
348                .try_get_property_mut(&ValueContainer::from(0u32))
349                .unwrap();
350            let mut inner_list = inner.try_as_mut::<List>().unwrap();
351            assert_matches!(inner_list.get_update_callback_data(), Some(UpdateCallbackData {
352                path,
353                ..
354            }) if path == &vec![ValueContainer::local(0u32)]);
355
356            // reset callback tracking
357            callback_updates.borrow_mut().clear();
358
359            // Push to inner list value (should trigger callback)
360            inner_list
361                .try_update(
362                    UpdateOperation::append_entry(ValueContainer::from(6)),
363                    Some(TransceiverId::Local),
364                    &cache,
365                )
366                .expect("Failed to push value to inner list");
367        }
368
369        {
370            let updates = callback_updates.borrow();
371            assert_eq!(updates.len(), 1);
372            assert_eq!(
373                updates[0].operation(),
374                &UpdateOperation::append_entry(ValueContainer::from(6))
375            );
376            assert_eq!(updates[0].path(), &vec![ValueContainer::local(0u32)]);
377        }
378
379        // reset callback tracking
380        callback_updates.borrow_mut().clear();
381
382        // Update inner list via outer list and check that callback is triggered with correct path
383        list.try_update_collapsed_local_inner(
384            UpdateOperation::set_entry(
385                0u32.into(),
386                ValueContainer::from(List::from(vec![7])),
387            ),
388            vec![ValueContainer::local(0u32)],
389            Some(TransceiverId::Local),
390            &cache,
391        )
392        .expect("Failed to set inner list value");
393
394        {
395            let updates = callback_updates.borrow();
396            assert_eq!(updates.len(), 1);
397            assert_eq!(
398                updates[0].operation(),
399                &UpdateOperation::set_entry(
400                    0u32.into(),
401                    ValueContainer::from(List::from(vec![7]))
402                )
403            );
404            assert_eq!(updates[0].path(), &vec![ValueContainer::local(0u32)]);
405        }
406
407        // reset callback tracking
408        callback_updates.borrow_mut().clear();
409
410        // update inner list with normal push method directly
411        {
412            // get inner list value
413            let inner = list
414                .try_get_property_mut(&ValueContainer::from(0u32))
415                .unwrap();
416            let mut inner_list = inner.try_as_mut::<List>().unwrap();
417            inner_list.push(42);
418        }
419
420        {
421            let updates = callback_updates.borrow();
422            assert_eq!(updates.len(), 1);
423            assert_eq!(
424                updates[0].operation(),
425                &UpdateOperation::append_entry(ValueContainer::from(42))
426            );
427            assert_eq!(updates[0].path(), &vec![ValueContainer::local(0u32)]);
428        }
429
430        // reset callback tracking
431        callback_updates.borrow_mut().clear();
432
433        // add new inner list
434        {
435            // add new inner list value
436            let new_inner = ValueContainer::from(List::from(vec![7]));
437            list.try_update_collapsed_local_inner(
438                UpdateOperation::set_entry(1u32.into(), new_inner),
439                vec![],
440                Some(TransceiverId::Local),
441                &cache,
442            )
443            .unwrap();
444
445            // check that the callback data was set on the new inner list
446            let inner = list
447                .try_get_property_mut(&ValueContainer::from(1u32))
448                .unwrap();
449            let mut inner_list = inner.try_as_mut::<List>().unwrap();
450
451            assert_matches!(inner_list.get_update_callback_data(), Some(UpdateCallbackData {
452                path,
453                ..
454            }) if path == &vec![ValueContainer::local(1u32)]);
455
456            // check that update callback was triggered
457            {
458                let updates = callback_updates.borrow();
459                assert_eq!(updates.len(), 1);
460                assert_eq!(
461                    updates[0].operation(),
462                    &UpdateOperation::set_entry(
463                        1u32.into(),
464                        ValueContainer::from(List::from(vec![7]))
465                    )
466                );
467                assert_eq!(updates[0].path(), &vec![]);
468            }
469
470            // reset callback tracking
471            callback_updates.borrow_mut().clear();
472
473            // clear inner list should trigger callback
474            inner_list.clear();
475        }
476
477        {
478            let updates = callback_updates.borrow();
479            assert_eq!(updates.len(), 1);
480            assert_eq!(updates[0].operation(), &UpdateOperation::clear());
481            assert_eq!(updates[0].path(), &vec![ValueContainer::local(1u32)]);
482        }
483    }
484}