github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/network/codec/cbor/encoder.go (about) 1 package cbor 2 3 import ( 4 "bytes" 5 "fmt" 6 7 "github.com/fxamacker/cbor/v2" 8 9 cborcodec "github.com/onflow/flow-go/model/encoding/cbor" 10 "github.com/onflow/flow-go/network/codec" 11 _ "github.com/onflow/flow-go/utils/binstat" 12 ) 13 14 // Encoder is an encoder to write serialized CBOR to a writer. 15 type Encoder struct { 16 enc *cbor.Encoder 17 } 18 19 // Encode will convert the given message into CBOR and write it to the 20 // underlying encoder, followed by a new line. 21 func (e *Encoder) Encode(v interface{}) error { 22 // encode the value 23 code, what, err := codec.MessageCodeFromInterface(v) 24 if err != nil { 25 return fmt.Errorf("could not determine envelope code string: %w", err) 26 } 27 28 // encode the payload 29 //bs1 := binstat.EnterTime(fmt.Sprintf("%s%s%s:%d", binstat.BinNet, ":strm<1(cbor)", what, code)) // e.g. ~3net::strm<1(cbor)CodeEntityRequest:23 30 var data bytes.Buffer 31 _ = data.WriteByte(code.Uint8()) 32 encoder := cborcodec.EncMode.NewEncoder(&data) 33 err = encoder.Encode(v) 34 //binstat.LeaveVal(bs1, int64(data.Len())) 35 if err != nil { 36 return fmt.Errorf("could not encode cbor payload with message code %d aka %s: %w", code, what, err) // e.g. 2, "CodeBlockProposal", <CBOR error> 37 } 38 39 // encode / append the envelope code and write to stream 40 //bs2 := binstat.EnterTime(binstat.BinNet+":strm<2(cbor)envelope2payload2iowriter") 41 dataBytes := data.Bytes() 42 err = e.enc.Encode(dataBytes) 43 //binstat.LeaveVal(bs2, int64(data.Len())) 44 if err != nil { 45 return fmt.Errorf("could not encode to stream: %w", err) 46 } 47 48 return nil 49 }