jonhoo / flurry

A port of Java's ConcurrentHashMap to Rust

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Hashmap lacks of get_mut API

xuchaoqian opened this issue · comments

The current design of hashmap API doesn't support nested structures well.

For example:

pub struct ConnectionPool {
  slots: FlurryHashMap<String, ConnectionSlot>,
}

pub struct ConnectionSlot {
  endpoint: String,
  connections: Vec<Connection>,
}

pub fn remove<S: AsRef>(&self, endpoint: S, connection: &Connection)
  let guard = self.slots.guard();
  self.slots.get(endpoint.as_ref(), &guard).map(|slot| {
    slot.remove(connection); // cannot borrow `*slot` as mutable, as it is behind a `&` reference
  });
}

It is unfortunately not possible to provide a get_mut interface to a concurrent hash-map like this without locks, because you need a mechanism for excluding other read operations while the get_mut borrow is active. Instead, with a concurrent map, you'll want to use a function like HashMap::compute_if_present, which lets you do something kind of like this. Otherwise, consider a lock-based concurrent map like dashmap, which does have get_mut.