-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathatomic.go
More file actions
78 lines (65 loc) · 2.36 KB
/
atomic.go
File metadata and controls
78 lines (65 loc) · 2.36 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
71
72
73
74
75
76
77
78
package rate
import (
"math"
"sync/atomic"
)
// atomicSliceUint64 is a slice of uint64 values with atomic
// operations. It provides thread-safe access to elements in the
// slice.
type atomicSliceUint64 []uint64
// newAtomicSliceUint64 creates a new atomicSliceUint64 with the
// specified size.
func newAtomicSliceUint64(size int) atomicSliceUint64 {
return make([]uint64, size)
}
// Get atomically loads and returns the value at the specified index.
func (a atomicSliceUint64) Get(index int) uint64 {
return atomic.LoadUint64(&a[index])
}
// Set atomically stores the value at the specified index.
func (a atomicSliceUint64) Set(index int, value uint64) {
atomic.StoreUint64(&a[index], value)
}
// CompareAndSwap atomically compares the value at the specified index
// with old and swaps it with new if they match. Returns true if the
// swap occurred.
func (a atomicSliceUint64) CompareAndSwap(index int, old, new uint64) bool {
return atomic.CompareAndSwapUint64(&a[index], old, new)
}
// Len returns the length of the atomic slice.
func (a atomicSliceUint64) Len() int {
return len(a)
}
// atomicSliceFloat64 is a slice of float64 values with atomic
// operations. It provides thread-safe access to elements in the
// slice. Float64 values are stored as uint64 bits for atomic
// operations.
type atomicSliceFloat64 []uint64
// newAtomicSliceFloat64 creates a new atomicSliceFloat64 with the
// specified size.
func newAtomicSliceFloat64(size int) atomicSliceFloat64 {
return make([]uint64, size)
}
// Get atomically loads and returns the float64 value at the specified
// index.
func (a atomicSliceFloat64) Get(index int) float64 {
bits := atomic.LoadUint64(&a[index])
return math.Float64frombits(bits)
}
// Set atomically stores the float64 value at the specified index.
func (a atomicSliceFloat64) Set(index int, value float64) {
bits := math.Float64bits(value)
atomic.StoreUint64(&a[index], bits)
}
// CompareAndSwap atomically compares the float64 value at the
// specified index with old and swaps it with new if they match.
// Returns true if the swap occurred.
func (a atomicSliceFloat64) CompareAndSwap(index int, old, new float64) bool {
oldBits := math.Float64bits(old)
newBits := math.Float64bits(new)
return atomic.CompareAndSwapUint64(&a[index], oldBits, newBits)
}
// Len returns the length of the atomic slice.
func (a atomicSliceFloat64) Len() int {
return len(a)
}