您会自动获得这些移动语义,并通过将大值放入 a 来实现轻量级移动Box
(即在堆上分配它们)。使用type ConcurrentHashMap<K, V> = Mutex<HashMap<K, V>>;
作为线程安全的哈希图(有多种方法可以改进),可能有:
use std::collections::{HashMap, RingBuf};
use std::sync::Mutex;
type ConcurrentHashMap<K, V> = Mutex<HashMap<K, V>>;
lazy_static! {
pub static ref MAP: ConcurrentHashMap<String, RingBuf<String>> = {
Mutex::new(HashMap::new())
}
}
fn send(message: String, address: String) {
MAP.lock()
// find the place this message goes
.entry(address)
.get()
// create a new RingBuf if this address was empty
.unwrap_or_else(|v| v.insert(RingBuf::new()))
// add the message on the back
.push_back(message)
}
fn recv(address: &str) -> Option<String> {
MAP.lock()
.get_mut(address)
// pull the message off the front
.and_then(|buf| buf.pop_front())
}
该代码使用lazy_static!
宏来实现全局哈希图(使用包装 , fwiw 的本地对象可能会更好Arc<ConcurrentHashMap<...>
,因为全局状态会使对程序行为的推理变得困难)。它还RingBuf
用作队列,以便消息为给定的address
. 如果您一次只希望支持一条消息,则类型可以是ConcurrentHashMap<String, String>
,send
可以变成MAP.lock().insert(address, message)
和recv
just MAP.lock().remove(address)
。
(注意。我没有编译这个,所以类型可能不完全匹配。)