-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbytes.go
More file actions
72 lines (62 loc) · 1.65 KB
/
bytes.go
File metadata and controls
72 lines (62 loc) · 1.65 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
// Copyright (c) 2020 Meng Huang (mhboy@outlook.com)
// This package is licensed under a MIT license that can be found in the LICENSE file.
package atomic
import (
"unsafe"
)
// bytesEqual reports whether a and b
// are the same length and contain the same bytes.
// A nil argument is equivalent to an empty slice.
func bytesEqual(a, b []byte) bool {
// Neither cmd/compile nor gccgo allocates for these string conversions.
return *(*string)(unsafe.Pointer(&a)) == *(*string)(unsafe.Pointer(&b))
}
// Bytes represents an []byte.
type Bytes struct {
v Value
}
// NewBytes returns a new Bytes.
func NewBytes(val []byte) *Bytes {
addr := &Bytes{}
addr.Store(val)
return addr
}
// Swap atomically stores new into *addr and returns the previous *addr value.
func (addr *Bytes) Swap(new []byte) (old []byte) {
for {
load := addr.v.Load()
if addr.v.compareAndSwap(load, new) {
return load.([]byte)
}
}
}
// CompareAndSwap executes the compare-and-swap operation for an []byte value.
func (addr *Bytes) CompareAndSwap(old, new []byte) (swapped bool) {
load := addr.v.Load()
if !bytesEqual(old, load.([]byte)) {
return false
}
return addr.v.compareAndSwap(load, new)
}
// Add atomically adds delta to *addr and returns the new value.
func (addr *Bytes) Add(delta []byte) (new []byte) {
for {
old := addr.v.Load()
new = append(old.([]byte), delta...)
if addr.v.compareAndSwap(old, new) {
return
}
}
}
// Load atomically loads *addr.
func (addr *Bytes) Load() (val []byte) {
v := addr.v.Load()
if v == nil {
return nil
}
return v.([]byte)
}
// Store atomically stores val into *addr.
func (addr *Bytes) Store(val []byte) {
addr.v.Store(val)
}