1
0

safemap.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright 2014 beego Author. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package utils
  15. import (
  16. "sync"
  17. )
  18. // BeeMap is a map with lock
  19. type BeeMap struct {
  20. lock *sync.RWMutex
  21. bm map[interface{}]interface{}
  22. }
  23. // NewBeeMap return new safemap
  24. func NewBeeMap() *BeeMap {
  25. return &BeeMap{
  26. lock: new(sync.RWMutex),
  27. bm: make(map[interface{}]interface{}),
  28. }
  29. }
  30. // Get from maps return the k's value
  31. func (m *BeeMap) Get(k interface{}) interface{} {
  32. m.lock.RLock()
  33. defer m.lock.RUnlock()
  34. if val, ok := m.bm[k]; ok {
  35. return val
  36. }
  37. return nil
  38. }
  39. // Set Maps the given key and value. Returns false
  40. // if the key is already in the map and changes nothing.
  41. func (m *BeeMap) Set(k interface{}, v interface{}) bool {
  42. m.lock.Lock()
  43. defer m.lock.Unlock()
  44. if val, ok := m.bm[k]; !ok {
  45. m.bm[k] = v
  46. } else if val != v {
  47. m.bm[k] = v
  48. } else {
  49. return false
  50. }
  51. return true
  52. }
  53. // Check Returns true if k is exist in the map.
  54. func (m *BeeMap) Check(k interface{}) bool {
  55. m.lock.RLock()
  56. defer m.lock.RUnlock()
  57. _, ok := m.bm[k]
  58. return ok
  59. }
  60. // Delete the given key and value.
  61. func (m *BeeMap) Delete(k interface{}) {
  62. m.lock.Lock()
  63. defer m.lock.Unlock()
  64. delete(m.bm, k)
  65. }
  66. // Items returns all items in safemap.
  67. func (m *BeeMap) Items() map[interface{}]interface{} {
  68. m.lock.RLock()
  69. defer m.lock.RUnlock()
  70. r := make(map[interface{}]interface{})
  71. for k, v := range m.bm {
  72. r[k] = v
  73. }
  74. return r
  75. }
  76. // Count returns the number of items within the map.
  77. func (m *BeeMap) Count() int {
  78. m.lock.RLock()
  79. defer m.lock.RUnlock()
  80. return len(m.bm)
  81. }