mapbank.go 838 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package stringutil
  2. import "sync"
  3. type stringBank struct {
  4. lock sync.Mutex
  5. m map[string]string
  6. }
  7. func NewStringBank() StringBank {
  8. return &stringBank{
  9. m: make(map[string]string),
  10. }
  11. }
  12. func (sb *stringBank) LoadOrStore(key, value string) (string, bool) {
  13. sb.lock.Lock()
  14. if v, ok := sb.m[key]; ok {
  15. sb.lock.Unlock()
  16. return v, ok
  17. }
  18. sb.m[value] = value
  19. sb.lock.Unlock()
  20. return value, false
  21. }
  22. func (sb *stringBank) LoadOrStoreFunc(key string, f func() string) (string, bool) {
  23. sb.lock.Lock()
  24. if v, ok := sb.m[key]; ok {
  25. sb.lock.Unlock()
  26. return v, ok
  27. }
  28. // create the key and value using the func (the key could be deallocated later)
  29. value := f()
  30. sb.m[value] = value
  31. sb.lock.Unlock()
  32. return value, false
  33. }
  34. func (sb *stringBank) Clear() {
  35. sb.lock.Lock()
  36. sb.m = make(map[string]string)
  37. sb.lock.Unlock()
  38. }