/
bytestring.go
95 lines (80 loc) · 1.94 KB
/
bytestring.go
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package atomickit
import (
"reflect"
"sync/atomic"
"unsafe"
"github.com/insolar/vanilla/longbits"
"github.com/insolar/vanilla/throw"
)
func NewOnceByteString(v longbits.ByteString) OnceByteString {
header := (*reflect.StringHeader)(unsafe.Pointer(&v))
return OnceByteString{
len: Int{ len(v) },
str: unsafe.Pointer(header.Data),
}
}
type OnceByteString struct {
len Int
str unsafe.Pointer
}
func (p *OnceByteString) Load() longbits.ByteString {
s, _ := p.TryLoad()
return s
}
const (
strLenUpdating = -1
strLenZero = -2
)
func (p *OnceByteString) TryLoad() (longbits.ByteString, bool) {
ln := p.len.Load()
if ln <= 0 {
return "", ln == strLenZero
}
str := atomic.LoadPointer(&p.str)
if str == nil {
panic(throw.IllegalState())
}
var result string
resultHeader := (*reflect.StringHeader)(unsafe.Pointer(&result))
resultHeader.Len = ln
resultHeader.Data = uintptr(str)
return longbits.WrapStr(result), true
}
func (p *OnceByteString) StoreOnce(v longbits.ByteString) bool {
switch header := (*reflect.StringHeader)(unsafe.Pointer(&v)); {
case header.Len == 0:
if p.len.CompareAndSwap(0, strLenZero) {
return true
}
for i := 0; p.len.Load() == strLenUpdating; i++ {
spinWait(i)
}
return false
case !p.len.CompareAndSwap(0, strLenUpdating):
return false
default:
atomic.StorePointer(&p.str, unsafe.Pointer(header.Data))
p.len.Store(header.Len)
return true
}
}
func (p *OnceByteString) MustStore(v longbits.ByteString) {
if !p.StoreOnce(v) {
panic(throw.IllegalState())
}
}
func (p *OnceByteString) CompareAndStore(new longbits.ByteString) bool {
switch header := (*reflect.StringHeader)(unsafe.Pointer(&new)); {
case header.Len == 0:
return p.len.Load() == 0
case !p.len.CompareAndSwap(0, -1):
return p.Load() == new
default:
atomic.StorePointer(&p.str, unsafe.Pointer(header.Data))
p.len.Store(header.Len)
return true
}
}
func (p *OnceByteString) String() string {
return p.Load().String()
}