Skip to content

Commit 60d0cbe

Browse files
committed
Add insert_same extension to HashMap
1 parent e5a602e commit 60d0cbe

File tree

1 file changed

+14
-0
lines changed
  • src/librustc_data_structures

1 file changed

+14
-0
lines changed

src/librustc_data_structures/sync.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@
2929
//! `rustc_erase_owner!` erases a OwningRef owner into Erased or Erased + Send + Sync
3030
//! depending on the value of cfg!(parallel_queries).
3131
32+
use std::collections::HashMap;
33+
use std::hash::{Hash, BuildHasher};
3234
use std::cmp::Ordering;
3335
use std::fmt::Debug;
3436
use std::fmt::Formatter;
@@ -227,6 +229,18 @@ pub fn assert_sync<T: ?Sized + Sync>() {}
227229
pub fn assert_send_val<T: ?Sized + Send>(_t: &T) {}
228230
pub fn assert_send_sync_val<T: ?Sized + Sync + Send>(_t: &T) {}
229231

232+
pub trait HashMapExt<K, V> {
233+
/// Same as HashMap::insert, but it may panic if there's already an
234+
/// entry for `key` with a value not equal to `value`
235+
fn insert_same(&mut self, key: K, value: V);
236+
}
237+
238+
impl<K: Eq + Hash, V: Eq, S: BuildHasher> HashMapExt<K, V> for HashMap<K, V, S> {
239+
fn insert_same(&mut self, key: K, value: V) {
240+
self.entry(key).and_modify(|old| assert!(*old == value)).or_insert(value);
241+
}
242+
}
243+
230244
impl<T: Copy + Debug> Debug for LockCell<T> {
231245
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
232246
f.debug_struct("LockCell")

0 commit comments

Comments
 (0)