2014-04-12 05:18:18 +00:00
|
|
|
// Beego (http://beego.me/)
|
2014-07-03 15:40:21 +00:00
|
|
|
//
|
2014-04-12 05:18:18 +00:00
|
|
|
// @description beego is an open-source, high-performance web framework for the Go programming language.
|
2014-07-03 15:40:21 +00:00
|
|
|
//
|
2014-04-12 05:18:18 +00:00
|
|
|
// @link http://github.com/astaxie/beego for the canonical source repository
|
2014-07-03 15:40:21 +00:00
|
|
|
//
|
2014-04-12 05:18:18 +00:00
|
|
|
// @license http://github.com/astaxie/beego/blob/master/LICENSE
|
2014-07-03 15:40:21 +00:00
|
|
|
//
|
2014-04-12 05:18:18 +00:00
|
|
|
// @authors astaxie
|
2013-12-12 14:40:29 +00:00
|
|
|
package utils
|
2013-03-28 07:25:49 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
type BeeMap struct {
|
|
|
|
lock *sync.RWMutex
|
|
|
|
bm map[interface{}]interface{}
|
|
|
|
}
|
|
|
|
|
2014-02-07 08:07:31 +00:00
|
|
|
// NewBeeMap return new safemap
|
2013-03-28 07:25:49 +00:00
|
|
|
func NewBeeMap() *BeeMap {
|
|
|
|
return &BeeMap{
|
|
|
|
lock: new(sync.RWMutex),
|
|
|
|
bm: make(map[interface{}]interface{}),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-02-07 08:07:31 +00:00
|
|
|
// Get from maps return the k's value
|
2013-03-28 07:25:49 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2014-02-07 08:07:31 +00:00
|
|
|
// Delete the given key and value.
|
2013-03-28 07:25:49 +00:00
|
|
|
func (m *BeeMap) Delete(k interface{}) {
|
|
|
|
m.lock.Lock()
|
|
|
|
defer m.lock.Unlock()
|
|
|
|
delete(m.bm, k)
|
|
|
|
}
|
2013-08-06 08:13:45 +00:00
|
|
|
|
2014-02-07 08:07:31 +00:00
|
|
|
// Items returns all items in safemap.
|
2013-08-06 08:13:45 +00:00
|
|
|
func (m *BeeMap) Items() map[interface{}]interface{} {
|
|
|
|
m.lock.RLock()
|
|
|
|
defer m.lock.RUnlock()
|
2014-07-26 15:25:51 +00:00
|
|
|
r := make(map[interface{}]interface{})
|
|
|
|
for k, v := range m.bm {
|
|
|
|
r[k] = v
|
|
|
|
}
|
|
|
|
return r
|
2013-08-06 08:13:45 +00:00
|
|
|
}
|