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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
#![allow(unsafe_code)]

use std::collections::hash_map::{RandomState, Entry};
use std::collections::HashMap;
use std::borrow::{Borrow, BorrowMut};
use std::hash::Hash;
use std::ops::{Deref, DerefMut};
use crate::runtime::{RwLock, RwLockReadGuard, RwLockWriteGuard};

/// SyncMap impl the Send and Sync

/// it use of RwLock,so it's safe! but we went convert lifetime ,so use some lifetime convert unsafe method(but it is safe)

pub struct SyncMap<K, V> where K: Eq + Hash {
    pub shard: RwLock<HashMap<K, V, RandomState>>,
}

impl<'a, K: 'a + Eq + Hash, V: 'a> SyncMap<K, V> where K: Eq + Hash {
    pub fn new() -> Self {
        Self {
            shard: RwLock::new(HashMap::new())
        }
    }

    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            shard: RwLock::new(HashMap::with_capacity(capacity))
        }
    }

    pub async fn insert(&self, key: K, value: V) -> Option<V> {
        let mut w = self.shard.write().await;
        w.insert(key, value)
    }

    pub async fn remove<Q>(&self, key: &Q) -> Option<V>
        where
            K: Borrow<Q>,
            Q: Hash + Eq + ?Sized {
        let mut w = self.shard.write().await;
        w.remove(key)
    }

    pub async fn clear(&self){
        let mut w = self.shard.write().await;
        w.clear();
    }

    pub async fn shrink_to_fit(&self) {
        let mut w = self.shard.write().await;
        w.shrink_to_fit();
    }

    pub async fn reserve(&self, additional: usize) {
        let mut w = self.shard.write().await;
        w.reserve(additional)
    }

    pub async fn read(&self) -> RwLockReadGuard<'_, HashMap<K, V, RandomState>> {
        self.shard.read().await
    }

    pub async fn write(&self) -> RwLockWriteGuard<'_, HashMap<K, V, RandomState>> {
        self.shard.write().await
    }

    pub async fn get<Q>(&'a self, k: &Q) -> Option<Ref<'a, K, V>>
        where K: Borrow<Q>,
              Q: Hash + Eq + ?Sized {
        let mut get_ref = Ref::new(self.shard.read().await, None);
        unsafe {
            let v = get_ref._guard.get(k);
            if v.is_some() {
                let vptr = change_lifetime_const(v.unwrap());
                get_ref.v = Option::from(vptr);
                Some(get_ref)
            } else {
                None
            }
        }
    }

    pub async fn get_mut<Q>(&'a self, k: &Q) -> Option<RefMut<'a, K, V>>
        where K: Borrow<Q>,
              Q: Hash + Eq + ?Sized {
        let mut get_ref = RefMut::new(self.shard.write().await, None);
        unsafe {
            let v = get_ref._guard.get_mut(k);
            if v.is_some() {
                let vptr = change_lifetime_mut(v.unwrap());
                get_ref.v = Option::Some(vptr);
                Some(get_ref)
            } else {
                None
            }
        }
    }
}

pub unsafe fn change_lifetime_const<'a, 'b, T>(x: &'a T) -> &'b T {
    &*(x as *const T)
}

pub unsafe fn change_lifetime_mut<'a, 'b, T>(x: &'a mut T) -> &'b mut T {
    &mut *(x as *mut T)
}

#[derive(Debug)]
pub struct Ref<'a, K, V>
    where K: Eq + Hash {
    _guard: RwLockReadGuard<'a, HashMap<K, V, RandomState>>,
    v: Option<&'a V>,
}

impl<'a, K, V> Ref<'a, K, V> where K: Eq + Hash {
    pub fn new(guard: RwLockReadGuard<'a, HashMap<K, V, RandomState>>, v: Option<&'a V>) -> Self {
        let s = Self {
            _guard: guard,
            v: v,
        };
        s
    }
    pub fn value(&self) -> &V {
        self.v.unwrap()
    }
}

impl<'a, K: Eq + Hash, V> Deref for Ref<'a, K, V> {
    type Target = V;

    fn deref(&self) -> &V {
        &self.value()
    }
}

#[derive(Debug)]
pub struct RefMut<'a, K, V, S = RandomState> {
    _guard: RwLockWriteGuard<'a, HashMap<K, V, S>>,
    v: Option<&'a mut V>,
}

impl<'a, K: Eq + Hash, V> RefMut<'a, K, V> {
    pub fn new(guard: RwLockWriteGuard<'a, HashMap<K, V, RandomState>>, v: Option<&'a mut V>) -> Self {
        let s = Self {
            _guard: guard,
            v: v,
        };
        s
    }

    pub fn value(&self) -> &V {
        self.v.as_ref().unwrap()
    }

    pub fn value_mut(&mut self) -> &mut V {
        self.v.as_mut().unwrap()
    }
}


impl<'a, K: Eq + Hash, V> Deref for RefMut<'a, K, V> {
    type Target = V;

    fn deref(&self) -> &V {
        self.value()
    }
}

impl<'a, K: Eq + Hash, V> DerefMut for RefMut<'a, K, V> {
    fn deref_mut(&mut self) -> &mut V {
        self.value_mut()
    }
}


#[cfg(test)]
mod test {
    use std::collections::HashMap;
    use std::sync::Arc;
    use std::ops::Deref;
    use futures_util::StreamExt;
    use crate::sync::sync_map::SyncMap;
    use std::time::SystemTime;
    use chrono::Local;


    #[test]
    fn test_map() {
        let m = Arc::new(SyncMap::new());
        async_std::task::block_on(async {
            let v = m.insert(1, "default".to_string()).await;
            let r = m.get(&1).await;
            let rv = r.unwrap().v;
            println!("r:{:?}", &rv);
            assert_eq!("default", format!("{}", &rv.unwrap()));

            drop(rv);

            let mut mut_v = m.get_mut(&1).await.unwrap();
            *mut_v = "changed".to_string();
            drop(mut_v);
            let r = m.get(&1).await;
            println!("r:{:?}", &r.as_ref().unwrap().deref());
            assert_eq!("changed", format!("{}", &r.as_ref().unwrap().deref()));
        });
    }

    #[test]
    fn test_map_for() {
        let m = Arc::new(SyncMap::new());
        async_std::task::block_on(async {
            let mut lock= m.write().await;
            lock.insert(1,1);
            drop(lock);
            let mut lock= m.read().await;
            for (k,v) in lock.deref(){
               println!("k:{},v:{}",k,v);
            }
        });
    }


    //bench on windows10 40 nano/op.  It depends on the runtime(tokio/async_std) speed

    //test command:

    //cargo test --release --color=always --package rbatis-core --lib sync::sync_map::test::bench_test --no-fail-fast -- --exact -Z unstable-options --format=json --show-output

    #[test]
    fn bench_test(){
        let mut m = Arc::new(SyncMap::new());
        async_std::task::block_on(async {
            let s = m.insert(1, "default".to_string()).await;
            drop(s);

            let total = 100000;
            let now=Local::now().timestamp_millis();
            for current in 0..total{
                let v=  m.get(&1).await;
                if current == total - 1 {
                    let end = Local::now().timestamp_millis();
                    print_use_time(total,now as i64,end as i64);
                    break;
                }
            }
            m.shrink_to_fit().await;
            println!("done");
        });
    }

    fn print_use_time(total: i32, start: i64, end: i64) {
        let mut time = (end - start) as f64;
        time = time / 1000.0;
        println!("use Time: {} s,each:{} nano/op", time, time * 1000000000.0 / (total as f64));
    }
}