mirror of
https://github.com/astaxie/beego.git
synced 2024-12-22 16:30:48 +00:00
add safemap and test
This commit is contained in:
parent
1b715bcbea
commit
f78ceb82d9
58
safemap.go
Normal file
58
safemap.go
Normal file
@ -0,0 +1,58 @@
|
||||
package beego
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
type BeeMap struct {
|
||||
lock *sync.RWMutex
|
||||
bm map[interface{}]interface{}
|
||||
}
|
||||
|
||||
func NewBeeMap() *BeeMap {
|
||||
return &BeeMap{
|
||||
lock: new(sync.RWMutex),
|
||||
bm: make(map[interface{}]interface{}),
|
||||
}
|
||||
}
|
||||
|
||||
//Get from maps return the k's value
|
||||
func (m *BeeMap) Get(k interface{}) interface{} {
|
||||
m.lock.RLock()
|
||||
defer m.lock.RUnlock()
|
||||
if val, ok := m.bm[k]; ok {
|
||||
return val
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Maps the given key and value. Returns false
|
||||
// if the key is already in the map and changes nothing.
|
||||
func (m *BeeMap) Set(k interface{}, v interface{}) bool {
|
||||
m.lock.Lock()
|
||||
defer m.lock.Unlock()
|
||||
if val, ok := m.bm[k]; !ok {
|
||||
m.bm[k] = v
|
||||
} else if val != v {
|
||||
m.bm[k] = v
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Returns true if k is exist in the map.
|
||||
func (m *BeeMap) Check(k interface{}) bool {
|
||||
m.lock.RLock()
|
||||
defer m.lock.RUnlock()
|
||||
if _, ok := m.bm[k]; !ok {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (m *BeeMap) Delete(k interface{}) {
|
||||
m.lock.Lock()
|
||||
defer m.lock.Unlock()
|
||||
delete(m.bm, k)
|
||||
}
|
24
safemap_test.go
Normal file
24
safemap_test.go
Normal file
@ -0,0 +1,24 @@
|
||||
package beego
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Test_beemap(t *testing.T) {
|
||||
bm := NewBeeMap()
|
||||
if !bm.Set("astaxie", 1) {
|
||||
t.Error("set Error")
|
||||
}
|
||||
if !bm.Check("astaxie") {
|
||||
t.Error("check err")
|
||||
}
|
||||
|
||||
if v := bm.Get("astaxie"); v.(int) != 1 {
|
||||
t.Error("get err")
|
||||
}
|
||||
|
||||
bm.Delete("astaxie")
|
||||
if bm.Check("astaxie") {
|
||||
t.Error("delete err")
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user