github.com/matrixorigin/matrixone@v1.2.0/pkg/pb/proxy/proxy.go (about)

     1  // Copyright 2021 - 2023 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 proxy
    16  
    17  import (
    18  	"bufio"
    19  	"bytes"
    20  )
    21  
    22  func (i *ExtraInfo) Encode() ([]byte, error) {
    23  	data, err := i.Marshal()
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  	size := len(data)
    28  	ret := make([]byte, 2, len(data)+2)
    29  	ret[0] = uint8(size)
    30  	ret[1] = uint8(size >> 8)
    31  	ret = append(ret, data...)
    32  	return ret, nil
    33  }
    34  
    35  func (i *ExtraInfo) Decode(reader *bufio.Reader) error {
    36  	data, err := readData(reader)
    37  	if err != nil {
    38  		return err
    39  	}
    40  	return i.Unmarshal(data[2:])
    41  }
    42  
    43  // readData reads all data in the reader.
    44  func readData(reader *bufio.Reader) ([]byte, error) {
    45  	s, err := reader.Peek(2)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  	buf := bytes.NewBuffer(s)
    50  	size := uint16(buf.Bytes()[0]) + uint16(buf.Bytes()[1])<<8 + 2
    51  	data := make([]byte, size)
    52  	if reader.Buffered() < int(size) {
    53  		hr := 0
    54  		for hr < int(size) {
    55  			l, err := reader.Read(data[hr:])
    56  			if err != nil {
    57  				return nil, err
    58  			}
    59  			hr += l
    60  		}
    61  	} else {
    62  		_, err = reader.Read(data)
    63  		if err != nil {
    64  			return nil, err
    65  		}
    66  	}
    67  	return data, nil
    68  }