f78ceb82 by astaxie

add safemap and test

1 parent 1b715bcb
1 package beego
2
3 import (
4 "sync"
5 )
6
7 type BeeMap struct {
8 lock *sync.RWMutex
9 bm map[interface{}]interface{}
10 }
11
12 func NewBeeMap() *BeeMap {
13 return &BeeMap{
14 lock: new(sync.RWMutex),
15 bm: make(map[interface{}]interface{}),
16 }
17 }
18
19 //Get from maps return the k's value
20 func (m *BeeMap) Get(k interface{}) interface{} {
21 m.lock.RLock()
22 defer m.lock.RUnlock()
23 if val, ok := m.bm[k]; ok {
24 return val
25 }
26 return nil
27 }
28
29 // Maps the given key and value. Returns false
30 // if the key is already in the map and changes nothing.
31 func (m *BeeMap) Set(k interface{}, v interface{}) bool {
32 m.lock.Lock()
33 defer m.lock.Unlock()
34 if val, ok := m.bm[k]; !ok {
35 m.bm[k] = v
36 } else if val != v {
37 m.bm[k] = v
38 } else {
39 return false
40 }
41 return true
42 }
43
44 // Returns true if k is exist in the map.
45 func (m *BeeMap) Check(k interface{}) bool {
46 m.lock.RLock()
47 defer m.lock.RUnlock()
48 if _, ok := m.bm[k]; !ok {
49 return false
50 }
51 return true
52 }
53
54 func (m *BeeMap) Delete(k interface{}) {
55 m.lock.Lock()
56 defer m.lock.Unlock()
57 delete(m.bm, k)
58 }
1 package beego
2
3 import (
4 "testing"
5 )
6
7 func Test_beemap(t *testing.T) {
8 bm := NewBeeMap()
9 if !bm.Set("astaxie", 1) {
10 t.Error("set Error")
11 }
12 if !bm.Check("astaxie") {
13 t.Error("check err")
14 }
15
16 if v := bm.Get("astaxie"); v.(int) != 1 {
17 t.Error("get err")
18 }
19
20 bm.Delete("astaxie")
21 if bm.Check("astaxie") {
22 t.Error("delete err")
23 }
24 }
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!