rw_map.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package types
  2. import (
  3. "sync"
  4. "github.com/QuantumNous/new-api/common"
  5. )
  6. type RWMap[K comparable, V any] struct {
  7. data map[K]V
  8. mutex sync.RWMutex
  9. }
  10. func (m *RWMap[K, V]) UnmarshalJSON(b []byte) error {
  11. m.mutex.Lock()
  12. defer m.mutex.Unlock()
  13. m.data = make(map[K]V)
  14. return common.Unmarshal(b, &m.data)
  15. }
  16. func (m *RWMap[K, V]) MarshalJSON() ([]byte, error) {
  17. m.mutex.RLock()
  18. defer m.mutex.RUnlock()
  19. return common.Marshal(m.data)
  20. }
  21. func NewRWMap[K comparable, V any]() *RWMap[K, V] {
  22. return &RWMap[K, V]{
  23. data: make(map[K]V),
  24. }
  25. }
  26. func (m *RWMap[K, V]) Get(key K) (V, bool) {
  27. m.mutex.RLock()
  28. defer m.mutex.RUnlock()
  29. value, exists := m.data[key]
  30. return value, exists
  31. }
  32. func (m *RWMap[K, V]) Set(key K, value V) {
  33. m.mutex.Lock()
  34. defer m.mutex.Unlock()
  35. m.data[key] = value
  36. }
  37. func (m *RWMap[K, V]) AddAll(other map[K]V) {
  38. m.mutex.Lock()
  39. defer m.mutex.Unlock()
  40. for k, v := range other {
  41. m.data[k] = v
  42. }
  43. }
  44. func (m *RWMap[K, V]) Clear() {
  45. m.mutex.Lock()
  46. defer m.mutex.Unlock()
  47. m.data = make(map[K]V)
  48. }
  49. // ReadAll returns a copy of the entire map.
  50. func (m *RWMap[K, V]) ReadAll() map[K]V {
  51. m.mutex.RLock()
  52. defer m.mutex.RUnlock()
  53. copiedMap := make(map[K]V)
  54. for k, v := range m.data {
  55. copiedMap[k] = v
  56. }
  57. return copiedMap
  58. }
  59. func (m *RWMap[K, V]) Len() int {
  60. m.mutex.RLock()
  61. defer m.mutex.RUnlock()
  62. return len(m.data)
  63. }
  64. func LoadFromJsonString[K comparable, V any](m *RWMap[K, V], jsonStr string) error {
  65. m.mutex.Lock()
  66. defer m.mutex.Unlock()
  67. m.data = make(map[K]V)
  68. return common.Unmarshal([]byte(jsonStr), &m.data)
  69. }
  70. // LoadFromJsonStringWithCallback loads a JSON string into the RWMap and calls the callback on success.
  71. func LoadFromJsonStringWithCallback[K comparable, V any](m *RWMap[K, V], jsonStr string, onSuccess func()) error {
  72. m.mutex.Lock()
  73. defer m.mutex.Unlock()
  74. m.data = make(map[K]V)
  75. err := common.Unmarshal([]byte(jsonStr), &m.data)
  76. if err == nil && onSuccess != nil {
  77. onSuccess()
  78. }
  79. return err
  80. }
  81. // MarshalJSONString returns the JSON string representation of the RWMap.
  82. func (m *RWMap[K, V]) MarshalJSONString() string {
  83. bytes, err := m.MarshalJSON()
  84. if err != nil {
  85. return "{}"
  86. }
  87. return string(bytes)
  88. }