github.com/geniusesgroup/libgo@v0.0.0-20220713101832-828057a9d3d4/protocol/codec.go (about) 1 /* For license and copyright information please see LEGAL file in repository */ 2 3 package protocol 4 5 import "io" 6 7 // Codec wraps some other interfaces! 8 // Differencess: 9 // - Marshal() don't think about any other parts and make a byte slice and serialize data to it. 10 // - MarshalTo() care about the fact that serialized data must wrap with other data and serialize data in the given byte slice. 11 // - Encode() like MarshalTo() but encode to a buf not a byte slice by Buffer interface methods! buf can be a temp or final write location. 12 // Almost always Encode() use in old OS fashion, it will care about how to write data to respect performance. Usually by make temp fixed size buffer like bufio package. 13 type Codec interface { 14 MediaType() MediaType 15 CompressType() CompressType 16 Len() (ln int) 17 18 Decoder 19 Encoder 20 21 Unmarshaler 22 Marshaler 23 } 24 25 // Decoder is the interface that wraps the Decode method. 26 // 27 // Decode read and decode data from buffer until end of data or occur error. 28 type Decoder interface { 29 Decode(reader io.Reader) (err Error) 30 } 31 32 // Encoder is the interface that wraps the Encode & Len methods. 33 // 34 // Encode writes serialized(encoded) data to buf until there's no more data to write! 35 // Len return value n is the number of bytes that will written as encode data. 36 type Encoder interface { 37 Encode(writer io.Writer) (err error) 38 Len() (ln int) 39 } 40 41 // Unmarshaler is the interface that wraps the Unmarshal method. 42 // 43 // Unmarshal reads and decode data from given slice until end of data or occur error 44 type Unmarshaler interface { 45 Unmarshal(data []byte) (err Error) 46 } 47 48 // Marshaler is the interface that wraps the Marshal method. 49 // 50 // Marshal serialized(encoded) data and return the byte slice 51 // MarshalTo serialized(encoded) data to given slice. Slice cap-len must >= Len() 52 // Len return value n that is the number of bytes that will written by Marshal()||MarshalTo() 53 type Marshaler interface { 54 Marshal() (data []byte) 55 MarshalTo(data []byte) []byte 56 Len() (ln int) 57 } 58 59 type SerializeLen interface { 60 ComputeLen() (ln int) 61 Len() (ln int) 62 }