-
Notifications
You must be signed in to change notification settings - Fork 46
/
local.go
321 lines (262 loc) · 6.98 KB
/
local.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
//
// Copyright 2019 Insolar Technologies GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package reference
import (
"encoding/binary"
"encoding/json"
"fmt"
"io"
"strconv"
"strings"
"github.com/pkg/errors"
"github.com/insolar/insolar/longbits"
"github.com/insolar/insolar/pulse"
)
var byteOrder = binary.BigEndian
func NewRecordID(pn pulse.Number, hash longbits.Bits224) Local {
return NewLocal(pn, 0, hash) // scope is not allowed for RecordID
}
func NewLocal(pn pulse.Number, scope uint8, hash longbits.Bits224) Local {
if !pn.IsSpecialOrTimePulse() {
panic(fmt.Sprintf("illegal value: %d", pn))
}
return Local{pulseAndScope: pn.WithFlags(scope), hash: hash}
}
const JetDepthPosition = 0
type Local struct {
pulseAndScope uint32 // pulse + scope
hash longbits.Bits224
}
// IsEmpty - check for void
func (v Local) IsEmpty() bool {
return v.pulseAndScope == 0
}
// NotEmpty - check for non void
func (v Local) NotEmpty() bool {
return !v.IsEmpty()
}
func (v Local) GetPulseNumber() pulse.Number {
return pulse.OfUint32(v.pulseAndScope)
}
func (v Local) GetHash() longbits.Bits224 {
return v.hash
}
func (v Local) getScope() uint8 {
return uint8(pulse.FlagsOf(v.pulseAndScope))
}
func (v *Local) WriteTo(w io.Writer) (int64, error) {
n, err := w.Write(v.pulseAndScopeAsBytes())
if err != nil {
return int64(n), err
}
var n2 int64
n2, err = v.hash.WriteTo(w)
return int64(n) + n2, err
}
func (v *Local) Read(p []byte) (n int, err error) {
if len(p) < LocalBinaryPulseAndScopeSize {
return copy(p, v.pulseAndScopeAsBytes()), nil
}
byteOrder.PutUint32(p, v.pulseAndScope)
return LocalBinaryPulseAndScopeSize + copy(p[LocalBinaryPulseAndScopeSize:], v.hash.AsBytes()), nil
}
func (v Local) len() int {
return LocalBinaryPulseAndScopeSize + len(v.hash)
}
func (v *Local) AsByteString() longbits.ByteString {
return longbits.NewByteString(v.AsBytes())
}
func (v *Local) AsBytes() []byte {
val := make([]byte, v.len())
byteOrder.PutUint32(val, v.pulseAndScope)
_, _ = v.hash.Read(val[LocalBinaryPulseAndScopeSize:])
return val
}
func (v *Local) pulseAndScopeAsBytes() []byte {
val := make([]byte, LocalBinaryPulseAndScopeSize)
byteOrder.PutUint32(val, v.pulseAndScope)
return val
}
func (v *Local) AsReader() io.ByteReader {
return v.asReader(uint8(v.len()))
}
func (v *Local) asReader(limit uint8) *byteReader {
return &byteReader{v: v, s: limit}
}
func (v *Local) asWriter() *byteWriter {
return &byteWriter{v: v}
}
type byteReader struct {
v *Local
o uint8
s uint8
}
func (p *byteReader) ReadByte() (byte, error) {
switch p.o {
case 0, 1, 2, 3:
v := byte(p.v.pulseAndScope >> ((3 - p.o) << 3))
p.o++
return v, nil
default:
if p.o >= p.s {
return 0, io.EOF
}
p.o++
return p.v.hash[p.o-1-LocalBinaryPulseAndScopeSize], nil
}
}
var _ io.ByteWriter = &byteWriter{}
type byteWriter struct {
v *Local
o uint8
}
func (p *byteWriter) WriteByte(c byte) error {
switch p.o {
case 0, 1, 2, 3:
shift := (3 - p.o) << 3
p.v.pulseAndScope = uint32(c)<<shift | p.v.pulseAndScope&^(0xFF<<shift)
default:
if p.isFull() {
return io.ErrUnexpectedEOF
}
p.v.hash[p.o-LocalBinaryPulseAndScopeSize] = c
}
p.o++
return nil
}
func (p *byteWriter) isFull() bool {
return int(p.o) >= p.v.len()
}
// String implements stringer on ID and returns base58 encoded value
func (v Local) String() string {
repr, err := DefaultEncoder().EncodeRecord(&v)
if err != nil {
return ""
}
return repr
}
// Bytes returns byte slice of ID.
func (v Local) Bytes() []byte {
return v.AsBytes()
}
// Equal checks if reference points to the same record
func (v *Local) Equal(other Local) bool {
if v == nil {
return false
}
return v.pulseAndScope == other.pulseAndScope && v.hash == other.hash
}
func (v Local) Compare(other Local) int {
if v.pulseAndScope < other.pulseAndScope {
return -1
} else if v.pulseAndScope > other.pulseAndScope {
return 1
}
return v.hash.Compare(other.hash)
}
// Pulse returns a copy of Pulse part of ID.
func (v Local) Pulse() pulse.Number {
return v.GetPulseNumber()
}
// Hash returns a copy of Hash part of ID
func (v Local) Hash() []byte {
rv := make([]byte, len(v.hash))
copy(rv, v.hash[:])
return rv
}
// MarshalJSON serializes ID into JSONFormat
func (v *Local) MarshalJSON() ([]byte, error) {
if v == nil {
return json.Marshal(nil)
}
return json.Marshal(v.String())
}
func (v Local) MarshalBinary() ([]byte, error) {
return v.Marshal()
}
func (v Local) Marshal() ([]byte, error) {
return v.AsBytes(), nil
}
func (v Local) MarshalTo(data []byte) (int, error) {
if len(data) < LocalBinarySize {
return 0, errors.New("not enough bytes to marshal reference.Local")
}
return copy(data, v.AsBytes()), nil
}
func (v *Local) UnmarshalJSON(data []byte) error {
var repr interface{}
err := json.Unmarshal(data, &repr)
if err != nil {
return errors.Wrap(err, "failed to unmarshal reference.Local")
}
switch realRepr := repr.(type) {
case string:
intermidiate, err := DefaultDecoder().Decode(realRepr)
if err != nil {
return errors.Wrap(err, "failed to unmarshal reference.Local")
}
*v = intermidiate.addressLocal
case nil:
default:
return errors.Wrapf(err, "unexpected type %T when unmarshal reference.Local", repr)
}
return nil
}
func (v *Local) UnmarshalBinary(data []byte) error {
return v.Unmarshal(data)
}
func (v *Local) Unmarshal(data []byte) error {
if len(data) < LocalBinarySize {
return errors.New("not enough bytes to unmarshal reference.Global")
}
writer := v.asWriter()
for i := 0; i < LocalBinarySize; i++ {
_ = writer.WriteByte(data[i])
}
return nil
}
func (v Local) Size() int {
return LocalBinarySize
}
func (v Local) debugStringJet() string {
depth, prefix := int(v.hash[JetDepthPosition]), v.hash[1:]
if depth == 0 {
return "[JET 0 -]"
} else if depth > 8*(len(v.hash)-1) {
return fmt.Sprintf("[JET: <wrong format> %d %b]", depth, prefix)
}
res := strings.Builder{}
res.WriteString(fmt.Sprintf("[JET %d ", depth))
for i := 0; i < depth; i++ {
bytePos, bitPos := i/8, 7-i%8
byteValue := prefix[bytePos]
bitValue := byteValue >> uint(bitPos) & 0x01
bitString := strconv.Itoa(int(bitValue))
res.WriteString(bitString)
}
res.WriteString("]")
return res.String()
}
// DebugString prints ID in human readable form.
func (v *Local) DebugString() string {
if v == nil {
return NilRef
} else if v.Pulse().IsJet() {
// TODO: remove this branch after finish transition to JetID
return v.debugStringJet()
}
return fmt.Sprintf("[%d | %d | %s]", v.Pulse(), v.getScope(), v.String())
}