/ ledger / store / src / helpers / test_helpers / map / check_atomic_writes_are_batched.rs
check_atomic_writes_are_batched.rs
 1  // Copyright (c) 2019-2025 Alpha-Delta Network Inc.
 2  // This file is part of the deltavm library.
 3  
 4  // Licensed under the Apache License, Version 2.0 (the "License");
 5  // you may not use this file except in compliance with the License.
 6  // You may obtain a copy of the License at:
 7  
 8  // http://www.apache.org/licenses/LICENSE-2.0
 9  
10  // Unless required by applicable law or agreed to in writing, software
11  // distributed under the License is distributed on an "AS IS" BASIS,
12  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  // See the License for the specific language governing permissions and
14  // limitations under the License.
15  
16  use crate::helpers::Map;
17  
18  use std::borrow::Cow;
19  
20  pub fn check_atomic_writes_are_batched(map: impl for<'a> Map<'a, usize, String>) {
21      // The number of items that will be inserted into the map.
22      const NUM_ITEMS: usize = 10;
23  
24      // Sanity check.
25      assert!(map.iter_confirmed().next().is_none());
26  
27      /* test atomic insertions */
28  
29      // Start an atomic write batch.
30      map.start_atomic();
31  
32      // Queue (since a batch is in progress) NUM_ITEMS insertions.
33      for i in 0..NUM_ITEMS {
34          map.insert(i, i.to_string()).unwrap();
35          // Ensure that the item is queued for insertion.
36          assert_eq!(map.get_pending(&i), Some(Some(i.to_string())));
37          // Ensure that the item can be found with a speculative get.
38          assert_eq!(map.get_speculative(&i).unwrap(), Some(Cow::Owned(i.to_string())));
39      }
40  
41      // The map should still contain no items.
42      assert!(map.iter_confirmed().next().is_none());
43  
44      // Finish the current atomic write batch.
45      map.finish_atomic().unwrap();
46  
47      // Check that the items are present in the map now.
48      for i in 0..NUM_ITEMS {
49          assert_eq!(map.get_confirmed(&i).unwrap(), Some(Cow::Borrowed(&i.to_string())));
50      }
51  
52      /* test atomic removals */
53  
54      // Start an atomic write batch.
55      map.start_atomic();
56  
57      // Queue (since a batch is in progress) NUM_ITEMS removals.
58      for i in 0..NUM_ITEMS {
59          map.remove(&i).unwrap();
60          // Ensure that the item is NOT queued for insertion.
61          assert_eq!(map.get_pending(&i), Some(None));
62      }
63  
64      // The map should still contains all the items.
65      assert_eq!(map.iter_confirmed().count(), NUM_ITEMS);
66  
67      // Finish the current atomic write batch.
68      map.finish_atomic().unwrap();
69  
70      // Check that the map is empty now.
71      assert!(map.iter_confirmed().next().is_none());
72  }