-
Notifications
You must be signed in to change notification settings - Fork 8
/
encoder.go
658 lines (600 loc) · 16.5 KB
/
encoder.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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
// Copyright 2016 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vom
import (
"errors"
"fmt"
"io"
"v.io/v23/vdl"
"v.io/v23/verror"
)
func (v Version) String() string {
return fmt.Sprintf("Version%x", byte(v))
}
var (
errEmptyEncoderStack = errors.New("vom: empty encoder stack")
errEntriesMustSetLenHint = errors.New("vom: entries must set LenHint")
errLabelNotInType = verror.Register(pkgPath+".errLabelNotInType", verror.NoRetry, "{1:}{2:} enum label {3} doesn't exist in type {4}{:_}")
errUnsupportedInVOMVersion = verror.Register(pkgPath+".errUnsupportedInVOMVersion", verror.NoRetry, "{1:}{2:} {3} unsupported in vom version {4}{:_}")
errUnusedTypeIds = verror.Register(pkgPath+".errUnusedTypeIds", verror.NoRetry, "{1:}{2:} vom: some type ids unused during encode {:_}")
errUnusedAnys = verror.Register(pkgPath+".errUnusedAnys", verror.NoRetry, "{1:}{2:} vom: some anys unused during encode {:_}")
)
const (
typeIDListInitialSize = 16
anyLenListInitialSize = 16
)
// paddingLen must be large enough to hold the header in writeMsg.
const paddingLen = maxEncodedUintBytes * 2
// Encoder manages the transmission and marshaling of typed values to the other
// side of a connection.
type Encoder struct {
enc encoder81
}
// NewEncoder returns a new Encoder that writes to the given writer in the VOM
// binary format. The binary format is compact and fast.
func NewEncoder(w io.Writer) *Encoder {
return NewVersionedEncoder(DefaultVersion, w)
}
// NewVersionedEncoder returns a new Encoder that writes to the given writer with
// the specified version.
func NewVersionedEncoder(version Version, w io.Writer) *Encoder {
typeEnc := newTypeEncoderInternal(version, newEncoderForTypes(version, w))
return NewVersionedEncoderWithTypeEncoder(version, w, typeEnc)
}
// NewEncoderWithTypeEncoder returns a new Encoder that writes to the given
// writer, where types are encoded separately through the typeEnc.
func NewEncoderWithTypeEncoder(w io.Writer, typeEnc *TypeEncoder) *Encoder {
return NewVersionedEncoderWithTypeEncoder(DefaultVersion, w, typeEnc)
}
// NewVersionedEncoderWithTypeEncoder returns a new Encoder that writes to the
// given writer with the specified version, where types are encoded separately
// through the typeEnc.
func NewVersionedEncoderWithTypeEncoder(version Version, w io.Writer, typeEnc *TypeEncoder) *Encoder {
if !isAllowedVersion(version) {
panic(fmt.Sprintf("unsupported VOM version: %x", version))
}
return &Encoder{encoder81{
writer: w,
buf: newEncbuf(),
typeEnc: typeEnc,
sentVersionByte: false,
version: version,
}}
}
func newEncoderForTypes(version Version, w io.Writer) *encoder81 {
if !isAllowedVersion(version) {
panic(fmt.Sprintf("unsupported VOM version: %x", version))
}
buf := newEncbuf()
e := &encoder81{
writer: w,
buf: buf,
sentVersionByte: true,
version: version,
mode: encoderForTypes,
}
return e
}
func newEncoderForRawBytes(w io.Writer) *encoder81 {
// RawBytes doesn't need the types to be encoded, since it holds the in-memory
// representation. We still need a type encoder to collect the unique types,
// but we give it a dummy encoder that doesn't have any state set up.
typeEnc := newTypeEncoderInternal(DefaultVersion, &encoder81{
sentVersionByte: true,
version: DefaultVersion,
mode: encoderForRawBytes,
})
return &encoder81{
writer: w,
buf: newEncbuf(),
typeEnc: typeEnc,
sentVersionByte: true,
version: DefaultVersion,
mode: encoderForRawBytes,
}
}
// Encoder returns e as a vdl.Encoder.
func (e *Encoder) Encoder() vdl.Encoder {
return &e.enc
}
// Encode transmits the value v. Values of type T are encodable as long as the
// T is a valid vdl type.
func (e *Encoder) Encode(v interface{}) error {
return vdl.Write(&e.enc, v)
}
type encoderMode int
const (
encoderRegular encoderMode = iota
encoderForTypes // encoder81 is embedded in TypeEncoder
encoderForRawBytes // encoder81 is used to encode RawBytes
)
type encoder81 struct {
stack []encoderStackEntry
// We use buf to buffer up the encoded value. The buffering is necessary so
// that we can compute the total message length.
buf *encbuf
// Buffer for the header of messages with any or typeobject.
bufHeader *encbuf
// Underlying writer.
writer io.Writer
// All types are sent through typeEnc.
typeEnc *TypeEncoder
sentVersionByte bool
version Version
tids *typeIDList
anyLens *anyLenList
mid int64
hasLen, hasAny, hasTypeObject bool
typeIncomplete bool
isParentBytes bool // parent type is []byte or [N]byte
nextStartValueIsOptional bool // next StartValue is an optional type
// msgType captures the type of the top-level value. Unlike stack[0].Type, it
// also captures optionality for non-nil types.
msgType *vdl.Type
mode encoderMode
}
type encoderStackEntry struct {
Type *vdl.Type
Index int
LenHint int
NumStarted int
AnyRef anyStartRef
}
// We can only determine whether the next value is AnyType
// by checking the next type of the entry.
func (entry *encoderStackEntry) nextValueIsAny() bool {
switch tt := entry.Type; tt.Kind() {
case vdl.List, vdl.Array:
return tt.Elem() == vdl.AnyType
case vdl.Set:
return tt.Key() == vdl.AnyType
case vdl.Map:
// NumStarted is already incremented by the time we check it.
if entry.NumStarted%2 == 1 {
return tt.Key() == vdl.AnyType
} else {
return tt.Elem() == vdl.AnyType
}
case vdl.Struct, vdl.Union:
return tt.Field(entry.Index).Type == vdl.AnyType
}
return false
}
func (e *encoder81) top() *encoderStackEntry {
if len(e.stack) == 0 {
return nil
}
return &e.stack[len(e.stack)-1]
}
func (e *encoder81) encodeWireType(tid TypeId, wt wireType, typeIncomplete bool) error {
// RawBytes doesn't need type messages to be encoded, since it holds the types
// in-memory.
if e.mode == encoderForRawBytes {
return nil
}
// Set up the state that would normally be set in startMessage, and use
// VDLWrite to encode wt as a regular value.
e.mid = int64(-tid)
e.typeIncomplete = typeIncomplete
e.hasAny = false
e.hasTypeObject = false
e.hasLen = true
e.tids = nil
e.anyLens = nil
return wt.VDLWrite(e)
}
func (e *encoder81) SetNextStartValueIsOptional() {
e.nextStartValueIsOptional = true
}
func (e *encoder81) NilValue(tt *vdl.Type) error {
switch tt.Kind() {
case vdl.Any, vdl.Optional:
default:
return fmt.Errorf("concrete types disallowed for NilValue (type was %v)", tt)
}
// Handle StartValue logic.
top, isOptionalInsideAny := e.top(), false
if top == nil {
if err := e.startMessage(tt); err != nil {
return err
}
} else {
isOptionalInsideAny = top.nextValueIsAny() && tt.Kind() == vdl.Optional
}
var anyRef anyStartRef
if isOptionalInsideAny {
tid, err := e.typeEnc.encode(tt)
if err != nil {
return err
}
binaryEncodeUint(e.buf, e.tids.ReferenceTypeID(tid))
anyRef = e.anyLens.StartAny(e.buf.Len())
binaryEncodeUint(e.buf, uint64(anyRef.index))
}
// Encode the nil control byte.
binaryEncodeControl(e.buf, WireCtrlNil)
// Handle FinishValue logic.
if isOptionalInsideAny {
e.anyLens.FinishAny(anyRef, e.buf.Len())
}
if top == nil {
if err := e.finishMessage(); err != nil {
return err
}
}
e.nextStartValueIsOptional = false
return nil
}
func (e *encoder81) StartValue(tt *vdl.Type) error {
switch tt.Kind() {
case vdl.Any, vdl.Optional:
return fmt.Errorf("only concrete types allowed for StartValue (type was %v)", tt)
}
var anyRef anyStartRef
top := e.top()
if top == nil {
e.isParentBytes = false
msgType := tt
if e.nextStartValueIsOptional {
msgType = vdl.OptionalType(tt)
}
if err := e.startMessage(msgType); err != nil {
return err
}
} else {
e.isParentBytes = top.Type.IsBytes()
top.NumStarted++
// Handle Any types, which need the Any header to be written.
if top.nextValueIsAny() {
anyType := tt
if e.nextStartValueIsOptional {
anyType = vdl.OptionalType(tt)
}
tid, err := e.typeEnc.encode(anyType)
if err != nil {
return err
}
binaryEncodeUint(e.buf, e.tids.ReferenceTypeID(tid))
anyRef = e.anyLens.StartAny(e.buf.Len())
binaryEncodeUint(e.buf, uint64(anyRef.index))
}
}
// Add entry to the stack.
e.stack = append(e.stack, encoderStackEntry{
Type: tt,
Index: -1,
LenHint: -1,
AnyRef: anyRef,
})
e.nextStartValueIsOptional = false
return nil
}
func (e *encoder81) startMessage(tt *vdl.Type) error {
e.buf.Reset()
e.buf.Grow(paddingLen)
e.msgType = tt
if e.mode == encoderForTypes {
// We've already set up the state in encodeWireType.
return nil
}
if !e.sentVersionByte {
if _, err := e.writer.Write([]byte{byte(e.version)}); err != nil {
return err
}
e.sentVersionByte = true
}
tid, err := e.typeEnc.encode(tt)
if err != nil {
return err
}
e.hasLen = hasChunkLen(tt)
e.hasAny = containsAny(tt)
e.hasTypeObject = containsTypeObject(tt)
e.typeIncomplete = false
e.mid = int64(tid)
if e.hasAny || e.hasTypeObject {
e.tids = newTypeIDList()
} else {
e.tids = nil
}
if e.hasAny {
e.anyLens = newAnyLenList()
} else {
e.anyLens = nil
}
return nil
}
func (e *encoder81) FinishValue() error {
e.isParentBytes = false
oldStackTop := len(e.stack) - 1
if oldStackTop == -1 {
return errEmptyDecoderStack
}
anyRef := e.stack[oldStackTop].AnyRef
e.stack = e.stack[:oldStackTop]
if oldStackTop == 0 {
return e.finishMessage()
}
if newTop := e.stack[oldStackTop-1]; newTop.nextValueIsAny() {
e.anyLens.FinishAny(anyRef, e.buf.Len())
}
return nil
}
func (e *encoder81) finishMessage() error {
if e.mode == encoderForRawBytes {
// Only encode the value portion for RawBytes.
msg := e.buf.Bytes()
_, err := e.writer.Write(msg[paddingLen:])
return err
}
if e.typeIncomplete {
if _, err := e.writer.Write([]byte{WireCtrlTypeIncomplete}); err != nil {
return err
}
}
if e.hasAny || e.hasTypeObject {
ids := e.tids.NewIDs()
var anyLens []int
if e.hasAny {
anyLens = e.anyLens.NewAnyLens()
}
if e.bufHeader == nil {
e.bufHeader = newEncbuf()
} else {
e.bufHeader.Reset()
}
binaryEncodeInt(e.bufHeader, e.mid)
binaryEncodeUint(e.bufHeader, uint64(len(ids)))
for _, id := range ids {
binaryEncodeUint(e.bufHeader, uint64(id))
}
if e.hasAny {
binaryEncodeUint(e.bufHeader, uint64(len(anyLens)))
for _, anyLen := range anyLens {
binaryEncodeUint(e.bufHeader, uint64(anyLen))
}
}
msg := e.buf.Bytes()
if e.hasLen {
binaryEncodeUint(e.bufHeader, uint64(len(msg)-paddingLen))
}
if _, err := e.writer.Write(e.bufHeader.Bytes()); err != nil {
return err
}
_, err := e.writer.Write(msg[paddingLen:])
return err
}
msg := e.buf.Bytes()
header := msg[:paddingLen]
if e.hasLen {
start := binaryEncodeUintEnd(header, uint64(len(msg)-paddingLen))
header = header[:start]
}
start := binaryEncodeIntEnd(header, e.mid)
_, err := e.writer.Write(msg[start:])
return err
}
func (e *encoder81) NextEntry(done bool) error {
top := e.top()
if top == nil {
return errEmptyEncoderStack
}
top.Index++
if top.Index == 0 {
switch {
case top.Type.Kind() == vdl.Array:
binaryEncodeUint(e.buf, 0)
case top.LenHint >= 0:
binaryEncodeUint(e.buf, uint64(top.LenHint))
}
}
if done && top.Type.Kind() != vdl.Array && top.LenHint == -1 {
// TODO(toddw): Emit collection terminator.
// binaryEncodeControl(e.buf, WireCtrlCollectionTerminator)
return errEntriesMustSetLenHint
}
return nil
}
func (e *encoder81) NextField(index int) error {
top := e.top()
if top == nil {
return errEmptyEncoderStack
}
if index < -1 || index >= top.Type.NumField() {
return fmt.Errorf("vom: NextField called with invalid index %d", index)
}
if index == -1 {
if top.Type.Kind() == vdl.Struct {
binaryEncodeControl(e.buf, WireCtrlEnd)
}
return nil
}
binaryEncodeUint(e.buf, uint64(index))
top.Index = index
return nil
}
func (e *encoder81) SetLenHint(lenHint int) error {
top := e.top()
if top == nil {
return errEmptyEncoderStack
}
switch top.Type.Kind() {
case vdl.List, vdl.Set, vdl.Map:
default:
fmt.Errorf("SetLenHint illegal for type %v", top.Type)
}
top.LenHint = lenHint
return nil
}
func (e *encoder81) EncodeBool(value bool) error {
binaryEncodeBool(e.buf, value)
return nil
}
func (e *encoder81) EncodeUint(value uint64) error {
// Handle a special-case where normally single bytes are written out as
// variable sized numbers, which use 2 bytes to encode bytes > 127. But each
// byte contained in a list or array is written out as one byte. E.g.
// byte(0x81) -> 0xFF81 : single byte with variable-size
// []byte("\x81\x82") -> 0x028182 : each elem byte encoded as one byte
if e.isParentBytes {
e.buf.WriteOneByte(byte(value))
} else {
binaryEncodeUint(e.buf, value)
}
return nil
}
func (e *encoder81) EncodeInt(value int64) error {
binaryEncodeInt(e.buf, value)
return nil
}
func (e *encoder81) EncodeFloat(value float64) error {
binaryEncodeFloat(e.buf, value)
return nil
}
func (e *encoder81) EncodeBytes(value []byte) error {
top := e.top()
if top == nil {
return errEmptyEncoderStack
}
if top.Type.Kind() == vdl.Array {
binaryEncodeUint(e.buf, 0)
} else {
binaryEncodeUint(e.buf, uint64(len(value)))
}
e.buf.Write(value)
return nil
}
func (e *encoder81) EncodeString(value string) error {
top := e.top()
if top == nil {
return errEmptyEncoderStack
}
if tt := top.Type; tt.Kind() == vdl.Enum {
index := tt.EnumIndex(value)
if index < 0 {
return verror.New(errLabelNotInType, nil, value, tt)
}
binaryEncodeUint(e.buf, uint64(index))
} else {
binaryEncodeUint(e.buf, uint64(len(value)))
e.buf.WriteString(value)
}
return nil
}
func (e *encoder81) EncodeTypeObject(value *vdl.Type) error {
tid, err := e.typeEnc.encode(value)
if err != nil {
return err
}
binaryEncodeUint(e.buf, e.tids.ReferenceTypeID(tid))
return nil
}
// writeRawBytes writes rb to e. This only works if e at the top-level; if it
// has already encoded some values, rb.Data needs to be re-written with new
// indices for type ids and any lengths.
//
// REQUIRES: e.version == rb.Version && len(e.stack) == 0
//
// TODO(toddw): Code a variant of this that performs the re-writing.
func (e *encoder81) writeRawBytes(rb *RawBytes) error {
if rb.IsNil() {
return e.NilValue(rb.Type)
}
tt := rb.Type
if tt.Kind() == vdl.Optional {
e.SetNextStartValueIsOptional()
tt = tt.Elem()
}
if err := e.StartValue(tt); err != nil {
return err
}
if containsAny(tt) || containsTypeObject(tt) {
for _, refType := range rb.RefTypes {
tid, err := e.typeEnc.encode(refType)
if err != nil {
return err
}
e.tids.ReferenceTypeID(tid)
}
}
if containsAny(tt) {
e.anyLens.lens = rb.AnyLengths
}
e.buf.Write(rb.Data)
return e.FinishValue()
}
func newTypeIDList() *typeIDList {
return &typeIDList{
tids: make([]TypeId, 0, typeIDListInitialSize),
}
}
type typeIDList struct {
tids []TypeId
totalSent int
}
func (l *typeIDList) ReferenceTypeID(tid TypeId) uint64 {
for index, existingTid := range l.tids {
if existingTid == tid {
return uint64(index)
}
}
l.tids = append(l.tids, tid)
return uint64(len(l.tids) - 1)
}
func (l *typeIDList) Reset() error {
if l.totalSent != len(l.tids) {
return verror.New(errUnusedTypeIds, nil)
}
l.tids = l.tids[:0]
l.totalSent = 0
return nil
}
func (l *typeIDList) NewIDs() []TypeId {
var newIDs []TypeId
if l.totalSent < len(l.tids) {
newIDs = l.tids[l.totalSent:]
}
l.totalSent = len(l.tids)
return newIDs
}
func newAnyLenList() *anyLenList {
return &anyLenList{
lens: make([]int, 0, anyLenListInitialSize),
}
}
type anyStartRef struct {
index int // index into the anyLen list
marker int // position marker for the start of the any
}
type anyLenList struct {
lens []int
totalSent int
}
func (l *anyLenList) StartAny(startMarker int) anyStartRef {
l.lens = append(l.lens, 0)
index := len(l.lens) - 1
return anyStartRef{
index: index,
marker: startMarker + lenUint(uint64(index)),
}
}
func (l *anyLenList) FinishAny(start anyStartRef, endMarker int) {
l.lens[start.index] = endMarker - start.marker
}
func (l *anyLenList) Reset() error {
if l.totalSent != len(l.lens) {
return verror.New(errUnusedAnys, nil)
}
l.lens = l.lens[:0]
l.totalSent = 0
return nil
}
func (l *anyLenList) NewAnyLens() []int {
var newAnyLens []int
if l.totalSent < len(l.lens) {
newAnyLens = l.lens[l.totalSent:]
}
l.totalSent = len(l.lens)
return newAnyLens
}