forked from vanadium-archive/go.v23
/
dump.go
845 lines (802 loc) · 25.4 KB
/
dump.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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
// Copyright 2015 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 (
"bytes"
"fmt"
"io"
"v.io/v23/vdl"
"v.io/v23/verror"
)
var (
errDumperClosed = verror.Register(pkgPath+".errDumperClosed", verror.NoRetry, "{1:}{2:} vom: Dumper closed{:_}")
errDumperFlushed = verror.Register(pkgPath+".errDumperFlushed", verror.NoRetry, "{1:}{2:} vom: Dumper flushed{:_}")
)
// Dump returns a human-readable dump of the given vom data, in the default
// string format.
func Dump(data []byte) (string, error) {
var buf bytes.Buffer
d := NewDumper(NewDumpWriter(&buf))
_, err := d.Write(data)
d.Close()
return string(buf.Bytes()), err
}
// DumpWriter is the interface that describes how to write out dumps produced by
// the Dumper. Implement this interface to customize dump output behavior.
type DumpWriter interface {
// WriteAtom is called by the Dumper for each atom it decodes.
WriteAtom(atom DumpAtom)
// WriteStatus is called by the Dumper to indicate the status of the dumper.
WriteStatus(status DumpStatus)
}
// NewDumpWriter returns a DumpWriter that outputs dumps to w, writing each atom
// and status on its own line, in their default string format.
func NewDumpWriter(w io.Writer) DumpWriter {
return dumpWriter{w}
}
type dumpWriter struct {
w io.Writer
}
func (w dumpWriter) WriteAtom(atom DumpAtom) {
fmt.Fprintln(w.w, atom)
}
func (w dumpWriter) WriteStatus(status DumpStatus) {
id := verror.ErrorID(status.Err)
if status.MsgLen == 0 && status.MsgN == 0 && (id == errDumperFlushed.ID || id == errDumperClosed.ID) {
// Don't output status when we're waiting to decode the next message, and
// we're either flushed or closed, to avoid cluttering the output.
return
}
fmt.Fprintln(w.w, status)
}
// Dumper produces dumps of vom data. It implements the io.WriteCloser
// interface; Data is fed to the dumper via Write, and Close must be called at
// the end of usage to release resources.
//
// Dumps of vom data consist of a single stream of DumpAtom and DumpStatus.
// Each atom describes a single piece of the vom encoding; the vom encoding is
// composed of a stream of atoms. The status describes the state of the dumper
// at that point in the stream.
type Dumper struct {
// The Dumper only contains channels to communicate with the dumpWorker, which
// does all the actual work.
cmdChan chan<- dumpCmd
closeChan <-chan struct{}
}
var _ io.WriteCloser = (*Dumper)(nil)
// NewDumper returns a new Dumper, which writes dumps of vom data to w.
//
// Close must be called on the returned Dumper to release resources.
func NewDumper(w DumpWriter) *Dumper {
cmd, close := make(chan dumpCmd), make(chan struct{})
startDumpWorker(cmd, close, w)
return &Dumper{cmd, close}
}
// Close flushes buffered data and releases resources. Close must be called
// exactly once, when the dumper is no longer needed.
func (d *Dumper) Close() error {
d.Flush()
close(d.cmdChan)
<-d.closeChan
return nil
}
// Flush flushes buffered data, and causes the dumper to restart decoding at the
// start of a new message. This is useful if the previous data in the stream
// was corrupt, and subsequent data will be for new vom messages. Previously
// buffered type information remains intact.
func (d *Dumper) Flush() error {
done := make(chan error)
d.cmdChan <- dumpCmd{nil, done}
err := <-done
return err
}
// Status triggers an explicit dump of the current status of the dumper to the
// DumpWriter. Status is normally generated at the end of each each decoded
// message; call Status to get extra information for partial dumps and errors.
func (d *Dumper) Status() {
done := make(chan error)
d.cmdChan <- dumpCmd{[]byte{}, done}
<-done
}
// Write implements the io.Writer interface method. This is the mechanism by
// which data is fed into the dumper.
func (d *Dumper) Write(data []byte) (int, error) {
if len(data) == 0 {
// Nil data means Flush, and non-nil empty data means Status, so we must
// ensure that normal writes never send 0-length data.
return 0, nil
}
done := make(chan error)
d.cmdChan <- dumpCmd{data, done}
err := <-done
return len(data), err
}
type dumpCmd struct {
// data holds Write data, except nil means Flush, and empty means Status.
data []byte
// done is closed when the worker has finished the command.
done chan error
}
// dumpWorker does all the actual work, in its own goroutine. Commands are sent
// from the Dumper to the worker via the cmdChan, and the closeChan is closed
// when the worker has exited its goroutine.
//
// We run the worker in a separate goroutine to keep the dumping logic simple
// and synchronous; the worker essentially runs the regular vom decoder logic,
// annotated with extra dump information. In theory we could implement the
// dumper without any extra goroutines, but that would require implementing a
// vom decoder that explicitly maintained the decoding stack (rather than simple
// recursive calls), which doesn't seem worth it.
//
// The reason we re-implement the vom decoding logic in the work rather than
// just adding the appropriate annotations to the regular vom decoder is for
// performance; we don't want to bloat the regular decoder with lots of dump
// annotations.
type dumpWorker struct {
cmdChan <-chan dumpCmd
closeChan chan<- struct{}
// We hold regular decoding state, and output dump information to w.
w DumpWriter
buf *decbuf
typeDec *TypeDecoder
status DumpStatus
version Version
recReader *recordingReader
recDataReader *recordedDataReader
redDataDec *decoder81
// Each Write call on the Dumper is passed to us on the cmdChan. When we get
// around to processing the Write data, we buffer any extra data, and hold on
// to the done channel so that we can close it when all the data is processed.
data bytes.Buffer
lastWrite chan<- error
// Hold on to the done channel for Flush commands, so that we can close it
// when the worker actually finishes decoding the current message.
lastFlush chan<- error
}
func startDumpWorker(cmd <-chan dumpCmd, close chan<- struct{}, w DumpWriter) {
worker := &dumpWorker{
cmdChan: cmd,
closeChan: close,
w: w,
typeDec: newTypeDecoderInternal(nil),
}
worker.recReader = &recordingReader{r: worker}
worker.recDataReader = &recordedDataReader{reader: worker.recReader}
worker.redDataDec = &NewDecoder(worker.recDataReader).dec
worker.buf = newDecbuf(worker.recReader)
go worker.decodeLoop()
}
// Read implements the io.Reader method, and is our synchronization strategy.
// The worker decodeLoop is running in its own goroutine, and keeps trying to
// decode vom messages. When the decoder runs out of data, it will trigger a
// Read call.
//
// Thus we're guaranteed that when Read is called, the worker decodeLoop is
// blocked waiting on the results. This gives us a natural place to process all
// commands, and consume more data from Write calls.
func (d *dumpWorker) Read(data []byte) (int, error) {
// If we have any data buffered up, just return it.
if n, _ := d.data.Read(data); n > 0 || len(data) == 0 {
return n, nil
}
// Otherwise we're done with all the buffered data. Signal the last Write
// call that all data has been processed.
d.lastWriteDone(nil)
// Wait for commands on the the cmd channel.
for {
select {
case cmd, ok := <-d.cmdChan:
if !ok {
// Close called, return our special closed error.
return 0, verror.New(errDumperClosed, nil)
}
switch {
case cmd.data == nil:
// Flush called, return our special flushed error. The Flush is done
// when the decoderLoop starts with a new message.
d.lastFlush = cmd.done
return 0, verror.New(errDumperFlushed, nil)
case len(cmd.data) == 0:
// Status called.
d.writeStatus(nil, false)
cmd.done <- nil
close(cmd.done)
default:
// Write called. Copy as much as we can into data, writing leftover
// into our buffer. Hold on to the cmd.done channel, so we can close it
// when the data has all been read.
n := copy(data, cmd.data)
if n < len(cmd.data) {
d.data.Write(cmd.data[n:])
}
d.lastWrite = cmd.done
return n, nil
}
}
}
}
// decodeLoop runs a loop synchronously decoding messages. Calls to read from
// d.buf will eventually result in a call to d.Read, which allows us to handle
// special commands like Close, Flush and Status synchronously.
func (d *dumpWorker) decodeLoop() {
for {
err := d.decodeNextValue()
d.writeStatus(err, true)
switch {
case verror.ErrorID(err) == errDumperClosed.ID:
d.lastWriteDone(err)
d.lastFlushDone(err)
close(d.closeChan)
return
case err != nil:
// Any error causes us to flush our buffers; otherwise we run the risk of
// an infinite loop.
d.buf.Reset()
d.data.Reset()
d.lastWriteDone(err)
d.lastFlushDone(err)
}
}
}
func (d *dumpWorker) lastWriteDone(err error) {
if d.lastWrite != nil {
d.lastWrite <- err
close(d.lastWrite)
d.lastWrite = nil
}
}
func (d *dumpWorker) lastFlushDone(err error) {
if d.lastFlush != nil {
d.lastFlush <- err
close(d.lastFlush)
d.lastFlush = nil
}
}
// DumpStatus represents the state of the dumper. It is written to the
// DumpWriter at the end of decoding each value, and may also be triggered
// explicitly via Dumper.Status calls to get information for partial dumps.
type DumpStatus struct {
MsgId int64
MsgLen int
MsgN int
Buf []byte
Debug string
RefTypes []*vdl.Type
RefAnyLens []uint64
Value *vdl.Value
Err error
}
func (s DumpStatus) String() string {
ret := fmt.Sprintf("DumpStatus{MsgId: %d", s.MsgId)
if s.MsgLen != 0 {
ret += fmt.Sprintf(", MsgLen: %d", s.MsgLen)
}
if s.MsgN != 0 {
ret += fmt.Sprintf(", MsgN: %d", s.MsgN)
}
if len := len(s.Buf); len > 0 {
ret += fmt.Sprintf(`, Buf(%d): "%x"`, len, s.Buf)
}
if s.Debug != "" {
ret += fmt.Sprintf(", Debug: %q", s.Debug)
}
if s.Value.IsValid() {
ret += fmt.Sprintf(", Value: %v", s.Value)
}
if s.Err != nil {
ret += fmt.Sprintf(", Err: %v", s.Err)
}
return ret + "}"
}
func (a DumpAtom) String() string {
dataFmt := "%20v"
if _, isString := a.Data.Interface().(string); isString {
dataFmt = "%20q"
}
ret := fmt.Sprintf("%-20x %-15v "+dataFmt, a.Bytes, a.Kind, a.Data.Interface())
if a.Debug != "" {
ret += fmt.Sprintf(" [%s]", a.Debug)
}
return ret
}
// writeStatus writes the current decoding status to the the DumpWriter. It is
// called automatically after every message is decoded, and also on every error
// encountered during decoding. It is also triggered by manual calls to
// Dumper.Status.
func (d *dumpWorker) writeStatus(err error, doneDecoding bool) {
if doneDecoding {
d.status.Err = err
if err == nil {
// Successful decoding, don't include the last "waiting..." debug message.
d.status.Debug = ""
}
}
// If we're stuck in the middle of a Read, the data we have so far is in the
// decbuf. Grab the data here for debugging.
if buflen := d.buf.end - d.buf.beg; buflen > 0 {
d.status.Buf = make([]byte, buflen)
copy(d.status.Buf, d.buf.buf[d.buf.beg:d.buf.end])
} else {
d.status.Buf = nil
}
err = NewDecoder(bytes.NewReader(d.recReader.bytes)).Decode(&d.status.Value)
d.w.WriteStatus(d.status)
if doneDecoding {
d.status = DumpStatus{}
}
}
// prepareAtom sets the status.Debug message, and prepares the decbuf so that
// subsequent writeAtom calls can easily capture all data that's been read.
func (d *dumpWorker) prepareAtom(format string, v ...interface{}) {
d.status.Debug = fmt.Sprintf(format, v...)
d.buf.moveDataToFront()
}
// writeAtom writes an atom describing the chunk of data we just decoded. In
// order to capture the data that was read, we rely on prepareAtom being called
// before the writeAtom call.
//
// The mechanism to capture the data is subtle. In prepareAtom we moved all
// decbuf data to the front, setting decbuf.beg to 0. Here we assume that all
// data in the decbuf up to the new value of decbuf.beg is what was read.
//
// This is tricky, and somewhat error-prone. We're using this strategy so that
// we can share the raw decoding logic with the real decoder, while still
// keeping the raw decoding logic reasonably compact and fast.
func (d *dumpWorker) writeAtom(kind DumpKind, data Primitive, format string, v ...interface{}) {
var bytes []byte
if len := d.buf.beg; len > 0 {
bytes = make([]byte, len)
copy(bytes, d.buf.buf[:len])
}
d.w.WriteAtom(DumpAtom{
Kind: kind,
Bytes: bytes,
Data: data,
Debug: fmt.Sprintf(format, v...),
})
d.status.MsgN += len(bytes)
d.buf.moveDataToFront()
}
func (d *dumpWorker) decodeNextValue() error {
// Decode type messages until we get to the type of the next value.
valType, err := d.decodeValueType()
if err != nil {
return err
}
// Decode value message.
err = d.decodeValueMsg(valType)
d.recDataReader.End(d.buf.beg)
return err
}
func (d *dumpWorker) decodeValueType() (*vdl.Type, error) {
for {
// Decode the version byte. To make the dumper easier to use on partial
// data, the version byte is optional, and is allowed to appear before any
// type or value message. Note that this relies on 0x80 not being a valid
// first byte of regular messages.
if d.version == 0 {
d.prepareAtom("waiting for version byte")
if !d.buf.IsAvailable(1) {
if err := d.buf.Fill(1); err != nil {
return nil, err
}
}
switch version := Version(d.buf.PeekAvailableByte()); version {
case Version81:
d.version = version
d.buf.SkipAvailable(1)
d.writeAtom(DumpKindVersion, PrimitivePByte{byte(version)}, version.String())
d.writeStatus(nil, true)
}
}
d.prepareAtom("waiting for message ID or control code")
incomplete, err := binaryDecodeControlOnly(d.buf, WireCtrlTypeIncomplete)
if err != nil {
return nil, err
}
if incomplete {
d.writeAtom(DumpKindControl, PrimitivePControl{ControlKindIncompleteType}, "incomplete type")
d.prepareAtom("waiting for message ID")
}
id, err := binaryDecodeInt(d.buf)
if err != nil {
return nil, err
}
d.writeAtom(DumpKindMsgId, PrimitivePInt{id}, "")
d.status.MsgId = id
switch {
case id == 0:
return nil, verror.New(errDecodeZeroTypeID, nil)
case id > 0:
// This is a value message, the typeID is +id.
tid := TypeId(+id)
tt, err := d.typeDec.lookupType(tid)
if err != nil {
d.writeAtom(DumpKindValueMsg, PrimitivePUint{uint64(tid)}, "%v", err)
return nil, err
}
d.writeAtom(DumpKindValueMsg, PrimitivePUint{uint64(tid)}, "%v", tt)
return tt, nil
}
// This is a type message, the typeID is -id.
tid := TypeId(-id)
d.writeAtom(DumpKindTypeMsg, PrimitivePUint{uint64(tid)}, "")
// Decode the wireType like a regular value, and store it in typeDec. The
// type will actually be built when a value message arrives using this tid.
if err := d.decodeValueMsg(wireTypeType); err != nil {
return nil, err
}
var wt wireType
if _, err := d.redDataDec.decodeWireType(&wt); err != nil {
return nil, err
}
d.recDataReader.End(d.buf.beg)
if err := d.typeDec.addWireType(tid, wt); err != nil {
return nil, err
}
if !incomplete {
if err := d.typeDec.buildType(tid); d.version >= Version81 && err != nil {
return nil, err
}
}
d.writeStatus(nil, true)
}
}
// decodeValueMsg decodes the rest of the message assuming type t, handling the
// optional message length.
func (d *dumpWorker) decodeValueMsg(tt *vdl.Type) error {
if d.version >= Version81 && (containsAny(tt) || containsTypeObject(tt)) {
d.prepareAtom("waiting for reference type ids")
tidsLen, err := binaryDecodeLen(d.buf)
if err != nil {
return err
}
d.writeAtom(DumpKindTypeIdsLen, PrimitivePUint{uint64(tidsLen)}, "")
d.status.RefTypes = make([]*vdl.Type, tidsLen)
for i := range d.status.RefTypes {
d.prepareAtom("waiting for type id")
tid, err := binaryDecodeUint(d.buf)
if err != nil {
return err
}
d.status.RefTypes[i], err = d.typeDec.lookupType(TypeId(tid))
d.writeAtom(DumpKindTypeId, PrimitivePUint{tid}, "")
}
if containsAny(tt) {
d.prepareAtom("waiting for any length list length")
anyLensLen, err := binaryDecodeLen(d.buf)
if err != nil {
return err
}
d.writeAtom(DumpKindAnyLensLen, PrimitivePUint{uint64(anyLensLen)}, "")
d.status.RefAnyLens = make([]uint64, anyLensLen)
for i := 0; i < anyLensLen; i++ {
d.prepareAtom("waiting for any len")
anyMsgLen, err := binaryDecodeUint(d.buf)
if err != nil {
return err
}
d.status.RefAnyLens[i] = anyMsgLen
d.writeAtom(DumpKindAnyMsgLen, PrimitivePUint{anyMsgLen}, "")
}
}
}
if hasChunkLen(tt) {
d.prepareAtom("waiting for message len")
msgLen, err := binaryDecodeLen(d.buf)
if err != nil {
return err
}
d.writeAtom(DumpKindMsgLen, PrimitivePUint{uint64(msgLen)}, "")
d.status.MsgLen = msgLen
d.status.MsgN = 0 // Make MsgN match up with MsgLen when successful.
d.buf.SetLimit(msgLen)
}
err := d.decodeValue(tt)
leftover := d.buf.RemoveLimit()
switch {
case err != nil:
return err
case leftover > 0:
return verror.New(errLeftOverBytes, nil, leftover)
}
return nil
}
// decodeValue decodes the rest of the message assuming type tt.
func (d *dumpWorker) decodeValue(tt *vdl.Type) error {
ttFrom := tt
if tt.Kind() == vdl.Optional {
d.prepareAtom("waiting for optional control byte")
// If the type is optional, we expect to see either WireCtrlNil or the actual
// value, but not both. And thus, we can just peek for the WireCtrlNil here.
switch ctrl, err := binaryPeekControl(d.buf); {
case err != nil:
return err
case ctrl == WireCtrlNil:
d.buf.SkipAvailable(1)
d.writeAtom(DumpKindControl, PrimitivePControl{ControlKindNil}, "%v is nil", ttFrom)
return nil
}
tt = tt.Elem()
}
if tt.IsBytes() {
d.prepareAtom("waiting for bytes len")
len, err := binaryDecodeLenOrArrayLen(d.buf, ttFrom)
if err != nil {
return err
}
d.writeAtom(DumpKindByteLen, PrimitivePUint{uint64(len)}, "bytes len")
d.prepareAtom("waiting for bytes data")
data := make([]byte, len)
if err := d.buf.ReadIntoBuf(data); err != nil {
return err
}
d.writeAtom(DumpKindPrimValue, PrimitivePString{string(data)}, "bytes")
return nil
}
switch kind := tt.Kind(); kind {
case vdl.Bool:
d.prepareAtom("waiting for bool value")
var v bool
var err error
switch d.version {
case Version80:
v, err = binaryDecodeBool(d.buf)
default:
var uv uint64
uv, err = binaryDecodeUint(d.buf)
v = (uv == 1)
}
if err != nil {
return err
}
d.writeAtom(DumpKindPrimValue, PrimitivePBool{v}, "bool")
return nil
case vdl.Byte:
d.prepareAtom("waiting for byte value")
v, err := binaryDecodeUint(d.buf)
if err != nil {
return err
}
d.writeAtom(DumpKindPrimValue, PrimitivePByte{byte(v)}, "byte")
return nil
case vdl.Uint16, vdl.Uint32, vdl.Uint64:
d.prepareAtom("waiting for uint value")
v, err := binaryDecodeUint(d.buf)
if err != nil {
return err
}
d.writeAtom(DumpKindPrimValue, PrimitivePUint{v}, "uint")
return nil
case vdl.Int8, vdl.Int16, vdl.Int32, vdl.Int64:
d.prepareAtom("waiting for int value")
v, err := binaryDecodeInt(d.buf)
if err != nil {
return err
}
d.writeAtom(DumpKindPrimValue, PrimitivePInt{v}, "int")
return nil
case vdl.Float32, vdl.Float64:
d.prepareAtom("waiting for float value")
v, err := binaryDecodeFloat(d.buf)
if err != nil {
return err
}
d.writeAtom(DumpKindPrimValue, PrimitivePFloat{v}, "float")
return nil
case vdl.String:
d.prepareAtom("waiting for string len")
len, err := binaryDecodeLen(d.buf)
if err != nil {
return err
}
d.writeAtom(DumpKindByteLen, PrimitivePUint{uint64(len)}, "string len")
d.prepareAtom("waiting for string data")
data := make([]byte, len)
if err := d.buf.ReadIntoBuf(data); err != nil {
return err
}
d.writeAtom(DumpKindPrimValue, PrimitivePString{string(data)}, "string")
return nil
case vdl.Enum:
d.prepareAtom("waiting for enum index")
index, err := binaryDecodeUint(d.buf)
if err != nil {
return err
}
if index >= uint64(tt.NumEnumLabel()) {
d.writeAtom(DumpKindIndex, PrimitivePUint{index}, "out of range for %v", tt)
return verror.New(errIndexOutOfRange, nil)
}
label := tt.EnumLabel(int(index))
d.writeAtom(DumpKindIndex, PrimitivePUint{index}, "%v.%v", tt.Name(), label)
return nil
case vdl.TypeObject:
d.prepareAtom("waiting for typeobject ID")
id, err := binaryDecodeUint(d.buf)
if err != nil {
return err
}
var typeobj *vdl.Type
switch d.version {
case Version80:
typeobj, err = d.typeDec.lookupType(TypeId(id))
default:
if id >= uint64(len(d.status.RefTypes)) {
return fmt.Errorf("type index %d out of bounds", id)
}
typeobj = d.status.RefTypes[id]
}
if err != nil {
d.writeAtom(DumpKindTypeId, PrimitivePUint{id}, "%v", err)
return err
}
d.writeAtom(DumpKindTypeId, PrimitivePUint{id}, "%v", typeobj)
return nil
case vdl.Array, vdl.List:
d.prepareAtom("waiting for list len")
len, err := binaryDecodeLenOrArrayLen(d.buf, tt)
if err != nil {
return err
}
d.writeAtom(DumpKindValueLen, PrimitivePUint{uint64(len)}, "list len")
for ix := 0; ix < len; ix++ {
if err := d.decodeValue(tt.Elem()); err != nil {
return err
}
}
return nil
case vdl.Set:
d.prepareAtom("waiting for set len")
len, err := binaryDecodeLen(d.buf)
if err != nil {
return err
}
d.writeAtom(DumpKindValueLen, PrimitivePUint{uint64(len)}, "set len")
for ix := 0; ix < len; ix++ {
if err := d.decodeValue(tt.Key()); err != nil {
return err
}
}
return nil
case vdl.Map:
d.prepareAtom("waiting for map len")
len, err := binaryDecodeLen(d.buf)
if err != nil {
return err
}
d.writeAtom(DumpKindValueLen, PrimitivePUint{uint64(len)}, "map len")
for ix := 0; ix < len; ix++ {
if err := d.decodeValue(tt.Key()); err != nil {
return err
}
if err := d.decodeValue(tt.Elem()); err != nil {
return err
}
}
return nil
case vdl.Struct:
// Loop through decoding the 0-based field index and corresponding field.
for {
d.prepareAtom("waiting for struct field index")
switch ok, err := binaryDecodeControlOnly(d.buf, WireCtrlEnd); {
case err != nil:
return err
case ok:
d.writeAtom(DumpKindControl, PrimitivePControl{ControlKindEnd}, "%v END", tt.Name())
return nil
}
index, err := binaryDecodeUint(d.buf)
switch {
case err != nil:
return err
case index >= uint64(tt.NumField()):
d.writeAtom(DumpKindIndex, PrimitivePUint{index}, "out of range for %v", tt)
return verror.New(errIndexOutOfRange, nil)
}
ttfield := tt.Field(int(index))
d.writeAtom(DumpKindIndex, PrimitivePUint{index}, "%v.%v", tt.Name(), ttfield.Name)
if err := d.decodeValue(ttfield.Type); err != nil {
return err
}
}
case vdl.Union:
d.prepareAtom("waiting for union field index")
index, err := binaryDecodeUint(d.buf)
switch {
case err != nil:
return err
case index >= uint64(tt.NumField()):
d.writeAtom(DumpKindIndex, PrimitivePUint{index}, "out of range for %v", tt)
return verror.New(errIndexOutOfRange, nil)
}
ttfield := tt.Field(int(index))
if tt == wireTypeType {
// Pretty-print for wire type definition messages.
d.writeAtom(DumpKindWireTypeIndex, PrimitivePUint{index}, "%v", ttfield.Type.Name())
} else {
d.writeAtom(DumpKindIndex, PrimitivePUint{index}, "%v.%v", tt.Name(), ttfield.Name)
}
if err := d.decodeValue(ttfield.Type); err != nil {
return err
}
return nil
case vdl.Any:
d.prepareAtom("waiting for any typeID")
switch ok, err := binaryDecodeControlOnly(d.buf, WireCtrlNil); {
case err != nil:
return err
case ok:
d.writeAtom(DumpKindControl, PrimitivePControl{ControlKindNil}, "any(nil)")
return nil
}
switch id, err := binaryDecodeUint(d.buf); {
case err != nil:
return err
default:
var err error
var elemType *vdl.Type
switch d.version {
case Version80:
elemType, err = d.typeDec.lookupType(TypeId(id))
default:
if id >= uint64(len(d.status.RefTypes)) {
return fmt.Errorf("type index %d out of bounds", id)
}
elemType = d.status.RefTypes[id]
}
if err != nil {
d.writeAtom(DumpKindTypeId, PrimitivePUint{id}, "%v", err)
return err
}
d.writeAtom(DumpKindTypeId, PrimitivePUint{id}, "%v", elemType)
if d.version >= Version81 {
d.prepareAtom("waiting for any message length index")
switch index, err := binaryDecodeUint(d.buf); {
case err != nil:
return err
default:
if index >= uint64(len(d.status.RefAnyLens)) {
return fmt.Errorf("any len index %d out of bounds", index)
}
d.writeAtom(DumpKindAnyMsgLen, PrimitivePUint{index}, "len %v", d.status.RefAnyLens[index])
return d.decodeValue(elemType)
}
}
return d.decodeValue(elemType)
}
default:
panic(verror.New(errDecodeValueUnhandledType, nil, tt))
}
}
// recordingReader delegates reads to the underlying reader, but stores
// the resulting bytes.
type recordingReader struct {
bytes []byte // TODO(toddw) don't accumulate bytes forever
r io.Reader
}
func (r *recordingReader) Read(p []byte) (n int, err error) {
n, err = r.r.Read(p)
if n > 0 {
r.bytes = append(r.bytes, p[:n]...)
}
return
}
// recordedDataReader reads from the buffer of a recordingReader.
// Recording can continue while this reader is being used.
type recordedDataReader struct {
reader *recordingReader
pos int
}
func (r *recordedDataReader) Read(p []byte) (n int, err error) {
if r.pos == len(r.reader.bytes) && len(p) > 0 {
return 0, io.EOF
}
n = copy(p, r.reader.bytes[r.pos:])
r.pos += n
return
}
func (r *recordedDataReader) End(readInBuf int) {
r.pos += readInBuf
}