You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
1.5 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. package cmap
  2. import (
  3. tmsync "github.com/tendermint/tendermint/internal/libs/sync"
  4. )
  5. // CMap is a goroutine-safe map
  6. type CMap struct {
  7. m map[string]interface{}
  8. l tmsync.Mutex
  9. }
  10. func NewCMap() *CMap {
  11. return &CMap{
  12. m: make(map[string]interface{}),
  13. }
  14. }
  15. func (cm *CMap) Set(key string, value interface{}) {
  16. cm.l.Lock()
  17. cm.m[key] = value
  18. cm.l.Unlock()
  19. }
  20. // GetOrSet returns the existing value if present. Othewise, it stores `newValue` and returns it.
  21. func (cm *CMap) GetOrSet(key string, newValue interface{}) (value interface{}, alreadyExists bool) {
  22. cm.l.Lock()
  23. defer cm.l.Unlock()
  24. if v, ok := cm.m[key]; ok {
  25. return v, true
  26. }
  27. cm.m[key] = newValue
  28. return newValue, false
  29. }
  30. func (cm *CMap) Get(key string) interface{} {
  31. cm.l.Lock()
  32. val := cm.m[key]
  33. cm.l.Unlock()
  34. return val
  35. }
  36. func (cm *CMap) Has(key string) bool {
  37. cm.l.Lock()
  38. _, ok := cm.m[key]
  39. cm.l.Unlock()
  40. return ok
  41. }
  42. func (cm *CMap) Delete(key string) {
  43. cm.l.Lock()
  44. delete(cm.m, key)
  45. cm.l.Unlock()
  46. }
  47. func (cm *CMap) Size() int {
  48. cm.l.Lock()
  49. size := len(cm.m)
  50. cm.l.Unlock()
  51. return size
  52. }
  53. func (cm *CMap) Clear() {
  54. cm.l.Lock()
  55. cm.m = make(map[string]interface{})
  56. cm.l.Unlock()
  57. }
  58. func (cm *CMap) Keys() []string {
  59. cm.l.Lock()
  60. keys := make([]string, 0, len(cm.m))
  61. for k := range cm.m {
  62. keys = append(keys, k)
  63. }
  64. cm.l.Unlock()
  65. return keys
  66. }
  67. func (cm *CMap) Values() []interface{} {
  68. cm.l.Lock()
  69. items := make([]interface{}, 0, len(cm.m))
  70. for _, v := range cm.m {
  71. items = append(items, v)
  72. }
  73. cm.l.Unlock()
  74. return items
  75. }