map.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package yu_sync
  2. import "sync"
  3. type Map[K comparable, V any] struct {
  4. lock sync.Mutex
  5. hash map[K]V
  6. }
  7. func (t *Map[K, V]) Set(key K, val V) {
  8. t.lock.Lock()
  9. defer t.lock.Unlock()
  10. if t.hash == nil {
  11. t.hash = make(map[K]V)
  12. }
  13. t.hash[key] = val
  14. }
  15. func (t *Map[K, V]) Get(key K) (val V, ok bool) {
  16. t.lock.Lock()
  17. defer t.lock.Unlock()
  18. if t.hash == nil {
  19. return
  20. }
  21. val, ok = t.hash[key]
  22. return
  23. }
  24. func (t *Map[K, V]) GetDelete(key K) (val V, ok bool) {
  25. t.lock.Lock()
  26. defer t.lock.Unlock()
  27. if t.hash == nil {
  28. return
  29. }
  30. if val, ok = t.hash[key]; ok {
  31. delete(t.hash, key)
  32. }
  33. return
  34. }
  35. func (t *Map[K, V]) For(on func(K, V)) {
  36. if on == nil {
  37. return
  38. }
  39. t.lock.Lock()
  40. defer t.lock.Unlock()
  41. for j_k, j_v := range t.hash {
  42. on(j_k, j_v)
  43. }
  44. return
  45. }
  46. func (t *Map[K, V]) ForDelete(on func(K, V)) {
  47. if on == nil {
  48. return
  49. }
  50. t.lock.Lock()
  51. defer t.lock.Unlock()
  52. for j_k, j_v := range t.hash {
  53. on(j_k, j_v)
  54. delete(t.hash, j_k)
  55. }
  56. return
  57. }
  58. func (t *Map[K, V]) Delete(key K) (ok bool) {
  59. t.lock.Lock()
  60. defer t.lock.Unlock()
  61. if t.hash == nil {
  62. return
  63. }
  64. _, ok = t.hash[key]
  65. delete(t.hash, key)
  66. return
  67. }
  68. func (t *Map[K, V]) Clear() {
  69. t.lock.Lock()
  70. defer t.lock.Unlock()
  71. t.hash = make(map[K]V)
  72. return
  73. }