1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
use runtime::{BtcAddress, H256};
use std::{borrow::Borrow, collections::HashMap, hash::Hash};
use tokio::sync::{Mutex, MutexGuard};
#[derive(Debug, Default)]
pub struct ReversibleHashMap<K, V>((HashMap<K, V>, HashMap<V, K>));
impl<K, V> ReversibleHashMap<K, V>
where
K: Hash + Eq + Clone,
V: Hash + Eq + Clone,
{
pub fn new() -> ReversibleHashMap<K, V> {
ReversibleHashMap((HashMap::new(), HashMap::new()))
}
pub fn insert(&mut self, k: K, v: V) -> (Option<K>, Option<V>) {
let k1 = self.0 .0.insert(k.clone(), v.clone());
let k2 = self.0 .1.insert(v, k);
(k2, k1)
}
pub fn remove_key<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
where
K: Borrow<Q>,
Q: Hash + Eq,
{
if let Some(v) = self.0 .0.remove(k) {
self.0 .1.remove(&v);
Some(v)
} else {
None
}
}
pub fn remove_value<Q: ?Sized>(&mut self, v: &Q) -> Option<K>
where
V: Borrow<Q>,
Q: Hash + Eq,
{
if let Some(k) = self.0 .1.remove(v) {
self.0 .0.remove(&k);
Some(k)
} else {
None
}
}
pub fn get_key_for_value<Q: ?Sized>(&mut self, v: &Q) -> Option<&K>
where
V: Borrow<Q>,
Q: Hash + Eq,
{
self.0 .1.get(v)
}
}
pub struct IssueRequests(Mutex<ReversibleHashMap<H256, BtcAddress>>);
impl IssueRequests {
pub fn new() -> Self {
Self::default()
}
pub(crate) async fn lock(&self) -> MutexGuard<'_, ReversibleHashMap<H256, BtcAddress>> {
self.0.lock().await
}
pub(crate) async fn insert(&self, issue_id: H256, address: BtcAddress) -> (Option<H256>, Option<BtcAddress>) {
self.0.lock().await.insert(issue_id, address)
}
pub(crate) async fn remove(&self, issue_id: &H256) -> Option<BtcAddress> {
self.0.lock().await.remove_key(issue_id)
}
}
impl Default for IssueRequests {
fn default() -> Self {
Self(Mutex::new(ReversibleHashMap::new()))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_add_key_value_pair() {
let mut rev_hash_map = ReversibleHashMap::<u32, u32>::new();
assert_eq!(rev_hash_map.insert(13, 37), (None, None));
assert_eq!(rev_hash_map.insert(13, 37), (Some(13), Some(37)));
assert_eq!(rev_hash_map.get_key_for_value(&37), Some(&13));
assert_eq!(rev_hash_map.remove_key(&13), Some(37));
assert_eq!(rev_hash_map.remove_key(&37), None);
}
}