2020-11-30 00:57:58 +00:00
|
|
|
package moreatomic
|
|
|
|
|
2020-12-19 10:35:13 +00:00
|
|
|
import (
|
|
|
|
"sync/atomic"
|
|
|
|
|
2021-06-02 02:53:19 +00:00
|
|
|
"github.com/diamondburned/arikawa/v3/internal/moreatomic/syncmod"
|
2020-12-19 10:35:13 +00:00
|
|
|
)
|
2020-11-30 00:57:58 +00:00
|
|
|
|
|
|
|
// Map is a thread-safe map that is a wrapper around sync.Map with slight API
|
|
|
|
// additions.
|
|
|
|
type Map struct {
|
2020-12-19 10:35:13 +00:00
|
|
|
val atomic.Value
|
2020-11-30 00:57:58 +00:00
|
|
|
ctor func() interface{}
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewMap(ctor func() interface{}) *Map {
|
2020-12-19 10:35:13 +00:00
|
|
|
sm := &Map{ctor: ctor}
|
|
|
|
sm.Reset()
|
|
|
|
return sm
|
2020-11-30 00:57:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Reset swaps the internal map out with a fresh one, dropping the old map. This
|
|
|
|
// method never errors.
|
|
|
|
func (sm *Map) Reset() error {
|
2020-12-19 10:35:13 +00:00
|
|
|
sm.val.Store(&syncmod.Map{New: sm.ctor})
|
2020-11-30 00:57:58 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// LoadOrStore loads an existing value or stores a new value created from the
|
|
|
|
// given constructor then return that value.
|
2020-11-30 01:19:05 +00:00
|
|
|
func (sm *Map) LoadOrStore(k interface{}) (lv interface{}, loaded bool) {
|
2020-12-19 10:35:13 +00:00
|
|
|
return sm.val.Load().(*syncmod.Map).LoadOrStore(k)
|
2020-11-30 00:57:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Load loads an existing value; it returns ok set to false if there is no
|
|
|
|
// value with that key.
|
|
|
|
func (sm *Map) Load(k interface{}) (lv interface{}, ok bool) {
|
2020-12-19 10:35:13 +00:00
|
|
|
return sm.val.Load().(*syncmod.Map).Load(k)
|
2020-11-30 00:57:58 +00:00
|
|
|
}
|