github.com/matrixorigin/matrixone@v0.7.0/pkg/vm/engine/tae/common/marshal.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 common
    16  
    17  import (
    18  	"encoding/binary"
    19  	"io"
    20  )
    21  
    22  func WriteString(str string, w io.Writer) (n int64, err error) {
    23  	buf := []byte(str)
    24  	if err = binary.Write(w, binary.BigEndian, uint16(len(buf))); err != nil {
    25  		return
    26  	}
    27  	wn, err := w.Write(buf)
    28  	return int64(wn + 2), err
    29  }
    30  
    31  func WriteBytes(b []byte, w io.Writer) (n int64, err error) {
    32  	if err = binary.Write(w, binary.BigEndian, uint16(len(b))); err != nil {
    33  		return
    34  	}
    35  	wn, err := w.Write(b)
    36  	return int64(wn + 2), err
    37  }
    38  
    39  func ReadString(r io.Reader) (str string, n int64, err error) {
    40  	strLen := uint16(0)
    41  	if err = binary.Read(r, binary.BigEndian, &strLen); err != nil {
    42  		return
    43  	}
    44  	buf := make([]byte, strLen)
    45  	if _, err = r.Read(buf); err != nil {
    46  		return
    47  	}
    48  	str = string(buf)
    49  	n = 2 + int64(strLen)
    50  	return
    51  }
    52  
    53  func ReadBytes(r io.Reader) (buf []byte, n int64, err error) {
    54  	strLen := uint16(0)
    55  	if err = binary.Read(r, binary.BigEndian, &strLen); err != nil {
    56  		return
    57  	}
    58  	buf = make([]byte, strLen)
    59  	if _, err = r.Read(buf); err != nil {
    60  		return
    61  	}
    62  	n = 2 + int64(strLen)
    63  	return
    64  }