github.com/zhigang2008/qrserver@v0.0.0-20150521135340-51313e45d270/dqs/util/safemap.go (about)

     1  package util
     2  
     3  import (
     4  	"sync"
     5  )
     6  
     7  type SafeMap struct {
     8  	lock *sync.RWMutex
     9  	bm   map[interface{}]interface{}
    10  }
    11  
    12  func NewSafeMap() *SafeMap {
    13  	return &SafeMap{
    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 *SafeMap) 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 *SafeMap) 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 *SafeMap) 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 *SafeMap) Delete(k interface{}) {
    55  	m.lock.Lock()
    56  	defer m.lock.Unlock()
    57  	delete(m.bm, k)
    58  }
    59  
    60  func (m *SafeMap) Items() map[interface{}]interface{} {
    61  	m.lock.RLock()
    62  	defer m.lock.RUnlock()
    63  	return m.bm
    64  }