fix: resolve atomic.Value usages with interface types

This commit is contained in:
wwqgtxx
2024-03-13 14:49:46 +08:00
parent 31d3614060
commit dceb8ee535
3 changed files with 18 additions and 7 deletions

View File

@@ -15,20 +15,31 @@ type TypedValue[T any] struct {
value atomic.Value
}
// tValue is a struct with determined type to resolve atomic.Value usages with interface types
// https://github.com/golang/go/issues/22550
//
// The intention to have an atomic value store for errors. However, running this code panics:
// panic: sync/atomic: store of inconsistently typed value into Value
// This is because atomic.Value requires that the underlying concrete type be the same (which is a reasonable expectation for its implementation).
// When going through the atomic.Value.Store method call, the fact that both these are of the error interface is lost.
type tValue[T any] struct {
value T
}
func (t *TypedValue[T]) Load() T {
value := t.value.Load()
if value == nil {
return DefaultValue[T]()
}
return value.(T)
return value.(tValue[T]).value
}
func (t *TypedValue[T]) Store(value T) {
t.value.Store(value)
t.value.Store(tValue[T]{value})
}
func (t *TypedValue[T]) Swap(new T) T {
old := t.value.Swap(new)
old := t.value.Swap(tValue[T]{new})
if old == nil {
return DefaultValue[T]()
}
@@ -36,7 +47,7 @@ func (t *TypedValue[T]) Swap(new T) T {
}
func (t *TypedValue[T]) CompareAndSwap(old, new T) bool {
return t.value.CompareAndSwap(old, new)
return t.value.CompareAndSwap(tValue[T]{old}, tValue[T]{new})
}
func (t *TypedValue[T]) MarshalJSON() ([]byte, error) {