1#![allow(non_camel_case_types)]
3#![allow(non_snake_case)]
4#![allow(non_upper_case_globals)]
5#![allow(dead_code)]
6
7use crate::common::{errcode,spin_lock::spin_lock_t};
8use std::collections::{hash_map::Iter,hash_map::IterMut,HashMap};
10use std::{cmp::Eq, hash::Hash};
11pub struct TsHashMap<K, V>
12where
13 K: std::cmp::Eq + std::hash::Hash,
14{
15 inner: HashMap<K, V>,
16 lock:spin_lock_t,
17}
18
19fn get_item<'a, K: Eq + Hash, V>(m: &'a HashMap<K, V>, k: &K) -> Result<&'a V, errcode::RESULT> {
20 match m.get(k) {
21 None => Err(errcode::ERROR_NOT_FOUND),
22 Some(v) => Ok(v),
23 }
24}
25
26impl<K, V> TsHashMap<K, V>
27where
28 K: std::cmp::Eq + std::hash::Hash,
29{
30 pub fn new(capacity:usize) -> Self {
31 let map = Self {
32 inner: HashMap::with_capacity(capacity),
33 lock:spin_lock_t::new(),
34 };
35 return map;
36 }
37 pub fn with_capacity(capacity:usize) -> Self {
38 Self::new(capacity)
39 }
40
41 pub fn get(&self, k: &K) -> Option<&V> {
42 self.lock.lock();
43 let v= self.inner.get(k);
44 self.lock.unlock();
45 return v
46
47 }
48 pub fn get_mut(&mut self, k: &K) -> Option<&mut V> {
49 self.lock.lock();
50 let v= self.inner.get_mut(k);
51 self.lock.unlock();
52 return v
53 }
54 pub fn contains_key(&self,k:&K)->bool {
55 return self.is_exist(k)
56 }
57 pub fn is_exist(&self,k:&K)->bool {
58
59 self.lock.lock();
60 let v= self.inner.contains_key(k);
61 self.lock.unlock();
62 return v
63
64 }
65
66 pub fn insert(&mut self, k: K, v: V) -> errcode::RESULT {
67 self.lock.lock();
68 let v= match self.inner.insert(k, v) {
69 None => errcode::RESULT_SUCCESS,
70 Some(_) => errcode::ERROR_ALREADY_EXIST,
71 };
72 self.lock.unlock();
73 return v
74
75 }
76
77 pub fn remove(&mut self, k: &K) -> Option<V> {
78 self.lock.lock();
79 let v= self.inner.remove(k);
80 self.lock.unlock();
81 return v
82 }
83 pub fn iter(&self) -> Iter<'_, K, V> {
110 self.lock.lock();
111 return self.inner.iter()
112 }
113
114 pub fn end_iter(&self) {
115 self.lock.unlock();
116 }
117
118 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
119 self.lock.lock();
120 return self.inner.iter_mut();
121 }
122 pub fn len(&self)->usize {
123 self.lock.lock();
124 let v= self.inner.len();
125 self.lock.unlock();
126 return v
127 }
128
129 pub fn capacity(&self)->usize {
130 self.lock.lock();
131 let v= self.inner.capacity();
132 self.lock.unlock();
133 return v
134 }
135
136 pub fn clear(&mut self) {
137 self.lock.lock();
138 self.inner.clear();
139 self.lock.unlock();
140 }
141}