github.com/matrixorigin/matrixone@v0.7.0/pkg/frontend/codec.go (about)

     1  // Copyright 2021 Matrix Origin
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package frontend
    16  
    17  import (
    18  	"context"
    19  	"io"
    20  
    21  	"github.com/fagongzi/goetty/v2/buf"
    22  	"github.com/fagongzi/goetty/v2/codec"
    23  	"github.com/matrixorigin/matrixone/pkg/common/moerr"
    24  )
    25  
    26  var (
    27  	errorInvalidLength0             = moerr.NewInvalidInput(context.Background(), "invalid length: 0")
    28  	errorLenOfWrittenNotEqLenOfData = moerr.NewInternalError(context.Background(), "len of written != len of the data")
    29  )
    30  
    31  const PacketHeaderLength = 4
    32  
    33  func NewSqlCodec() codec.Codec {
    34  	return &sqlCodec{}
    35  }
    36  
    37  type sqlCodec struct {
    38  }
    39  
    40  type Packet struct {
    41  	Length     int32
    42  	SequenceID int8
    43  	Payload    []byte
    44  }
    45  
    46  func (c *sqlCodec) Decode(in *buf.ByteBuf) (interface{}, bool, error) {
    47  	readable := in.Readable()
    48  	if readable < PacketHeaderLength {
    49  		return nil, false, nil
    50  	}
    51  
    52  	header := in.PeekN(0, PacketHeaderLength)
    53  	length := int32(uint32(header[0]) | uint32(header[1])<<8 | uint32(header[2])<<16)
    54  	if length == 0 {
    55  		return nil, false, errorInvalidLength0
    56  	}
    57  
    58  	sequenceID := int8(header[3])
    59  
    60  	if readable < int(length)+PacketHeaderLength {
    61  		return nil, false, nil
    62  	}
    63  
    64  	in.Skip(PacketHeaderLength)
    65  	in.SetMarkIndex(in.GetReadIndex() + int(length))
    66  	payload := in.ReadMarkedData()
    67  
    68  	packet := &Packet{
    69  		Length:     length,
    70  		SequenceID: sequenceID,
    71  		Payload:    payload,
    72  	}
    73  
    74  	return packet, true, nil
    75  }
    76  
    77  func (c *sqlCodec) Encode(data interface{}, out *buf.ByteBuf, writer io.Writer) error {
    78  	x := data.([]byte)
    79  	xlen := len(x)
    80  	tlen, err := out.Write(data.([]byte))
    81  	if err != nil {
    82  		return err
    83  	}
    84  	if tlen != xlen {
    85  		return errorLenOfWrittenNotEqLenOfData
    86  	}
    87  	return nil
    88  }