github.com/astaxie/beego@v1.12.3/utils/safemap.go (about)

     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  
    15  package utils
    16  
    17  import (
    18  	"sync"
    19  )
    20  
    21  // BeeMap is a map with lock
    22  type BeeMap struct {
    23  	lock *sync.RWMutex
    24  	bm   map[interface{}]interface{}
    25  }
    26  
    27  // NewBeeMap return new safemap
    28  func NewBeeMap() *BeeMap {
    29  	return &BeeMap{
    30  		lock: new(sync.RWMutex),
    31  		bm:   make(map[interface{}]interface{}),
    32  	}
    33  }
    34  
    35  // Get from maps return the k's value
    36  func (m *BeeMap) Get(k interface{}) interface{} {
    37  	m.lock.RLock()
    38  	defer m.lock.RUnlock()
    39  	if val, ok := m.bm[k]; ok {
    40  		return val
    41  	}
    42  	return nil
    43  }
    44  
    45  // Set Maps the given key and value. Returns false
    46  // if the key is already in the map and changes nothing.
    47  func (m *BeeMap) Set(k interface{}, v interface{}) bool {
    48  	m.lock.Lock()
    49  	defer m.lock.Unlock()
    50  	if val, ok := m.bm[k]; !ok {
    51  		m.bm[k] = v
    52  	} else if val != v {
    53  		m.bm[k] = v
    54  	} else {
    55  		return false
    56  	}
    57  	return true
    58  }
    59  
    60  // Check Returns true if k is exist in the map.
    61  func (m *BeeMap) Check(k interface{}) bool {
    62  	m.lock.RLock()
    63  	defer m.lock.RUnlock()
    64  	_, ok := m.bm[k]
    65  	return ok
    66  }
    67  
    68  // Delete the given key and value.
    69  func (m *BeeMap) Delete(k interface{}) {
    70  	m.lock.Lock()
    71  	defer m.lock.Unlock()
    72  	delete(m.bm, k)
    73  }
    74  
    75  // Items returns all items in safemap.
    76  func (m *BeeMap) Items() map[interface{}]interface{} {
    77  	m.lock.RLock()
    78  	defer m.lock.RUnlock()
    79  	r := make(map[interface{}]interface{})
    80  	for k, v := range m.bm {
    81  		r[k] = v
    82  	}
    83  	return r
    84  }
    85  
    86  // Count returns the number of items within the map.
    87  func (m *BeeMap) Count() int {
    88  	m.lock.RLock()
    89  	defer m.lock.RUnlock()
    90  	return len(m.bm)
    91  }