Repository navigation
Expand file tree
/
Copy pathpointer.go
More file actions
70 lines (60 loc) · 1.79 KB
/
Copy pathpointer.go
File metadata and controls
70 lines (60 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package xatomic
import (
"sync/atomic"
"unsafe"
)
// StorePointer atomically stores a pointer to a value.
// This is just a type-safe wrapper for atomic.LoadPointer.
//
// Consider also using atomic.Pointer, instead of this function.
func StorePointer[T any](dst **T, src *T) {
atomic.StorePointer(
(*unsafe.Pointer)(unsafe.Pointer(dst)),
unsafe.Pointer(src),
)
}
// LoadPointer atomically loads a pointer to a value.
// This is just a type-safe wrapper for atomic.LoadPointer.
//
// Consider also using atomic.Pointer, instead of this function.
func LoadPointer[T any](src **T) *T {
return (*T)(atomic.LoadPointer(
(*unsafe.Pointer)(unsafe.Pointer(src)),
))
}
// CompareAndSwapPointer atomically compares and swaps a pointer to a value.
// This is just a type-safe wrapper for atomic.CompareAndSwapPointer.
//
// Consider also using atomic.Pointer, instead of this function.
func CompareAndSwapPointer[T any](addr **T, old, new *T) bool {
return atomic.CompareAndSwapPointer(
(*unsafe.Pointer)(unsafe.Pointer(addr)),
unsafe.Pointer(old),
unsafe.Pointer(new),
)
}
// CompareAndSwapPointer atomically compares and swaps a pointer to a value.
// This is just a type-safe wrapper for atomic.SwapPointer.
//
// Consider also using atomic.Pointer, instead of this function.
func SwapPointer[T any](addr **T, new *T) *T {
return (*T)(atomic.SwapPointer(
(*unsafe.Pointer)(unsafe.Pointer(addr)),
unsafe.Pointer(new),
))
}
type Pointer[T any] struct {
Pointer *T
}
func (ptr *Pointer[T]) Store(new *T) {
StorePointer(&ptr.Pointer, new)
}
func (ptr *Pointer[T]) Load() *T {
return LoadPointer(&ptr.Pointer)
}
func (ptr *Pointer[T]) Swap(new *T) *T {
return SwapPointer(&ptr.Pointer, new)
}
func (ptr *Pointer[T]) CompareAndSwap(old, new *T) bool {
return CompareAndSwapPointer(&ptr.Pointer, old, new)
}