@@ -44,11 +44,23 @@ impl<K: Eq + Hash, V: Clone> LocatorCache<K, V> {
4444 self . cache . write ( ) . unwrap ( ) . insert ( key, value)
4545 }
4646
47+ /// Inserts multiple key-value pairs into the cache atomically.
48+ ///
49+ /// This method acquires a single write lock for all insertions, which is more
50+ /// efficient than calling `insert` multiple times when inserting many entries.
51+ pub fn insert_many ( & self , entries : impl IntoIterator < Item = ( K , V ) > ) {
52+ let mut cache = self . cache . write ( ) . unwrap ( ) ;
53+ for ( key, value) in entries {
54+ cache. insert ( key, value) ;
55+ }
56+ }
57+
4758 /// Returns a cloned value for the given key if it exists, otherwise computes
4859 /// and inserts the value using the provided closure.
4960 ///
5061 /// This method first checks with a read lock, then upgrades to a write lock
5162 /// if the value needs to be computed and inserted.
63+ #[ must_use]
5264 pub fn get_or_insert_with < F > ( & self , key : K , f : F ) -> Option < V >
5365 where
5466 F : FnOnce ( ) -> Option < V > ,
@@ -179,4 +191,22 @@ mod tests {
179191 values. sort ( ) ;
180192 assert_eq ! ( values, vec![ 42 , 100 ] ) ;
181193 }
194+
195+ #[ test]
196+ fn test_cache_insert_many ( ) {
197+ let cache: LocatorCache < String , i32 > = LocatorCache :: new ( ) ;
198+
199+ let entries = vec ! [
200+ ( "key1" . to_string( ) , 42 ) ,
201+ ( "key2" . to_string( ) , 100 ) ,
202+ ( "key3" . to_string( ) , 200 ) ,
203+ ] ;
204+
205+ cache. insert_many ( entries) ;
206+
207+ assert_eq ! ( cache. len( ) , 3 ) ;
208+ assert_eq ! ( cache. get( & "key1" . to_string( ) ) , Some ( 42 ) ) ;
209+ assert_eq ! ( cache. get( & "key2" . to_string( ) ) , Some ( 100 ) ) ;
210+ assert_eq ! ( cache. get( & "key3" . to_string( ) ) , Some ( 200 ) ) ;
211+ }
182212}
0 commit comments