github.com/datastax/go-cassandra-native-protocol@v0.0.0-20220706104457-5e8aad05cf90/primitive/bytes.go (about)

     1  // Copyright 2020 DataStax
     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 primitive
    16  
    17  import (
    18  	"errors"
    19  	"fmt"
    20  	"io"
    21  )
    22  
    23  // [bytes]
    24  
    25  func ReadBytes(source io.Reader) ([]byte, error) {
    26  	if length, err := ReadInt(source); err != nil {
    27  		return nil, fmt.Errorf("cannot read [bytes] length: %w", err)
    28  	} else if length < 0 {
    29  		return nil, nil
    30  	} else if length == 0 {
    31  		return []byte{}, nil
    32  	} else {
    33  		decoded := make([]byte, length)
    34  		if _, err := io.ReadFull(source, decoded); err != nil {
    35  			return nil, fmt.Errorf("cannot read [bytes] content: %w", err)
    36  		}
    37  		return decoded, nil
    38  	}
    39  }
    40  
    41  func WriteBytes(b []byte, dest io.Writer) error {
    42  	if b == nil {
    43  		if err := WriteInt(-1, dest); err != nil {
    44  			return fmt.Errorf("cannot write null [bytes]: %w", err)
    45  		}
    46  	} else {
    47  		length := len(b)
    48  		if err := WriteInt(int32(length), dest); err != nil {
    49  			return fmt.Errorf("cannot write [bytes] length: %w", err)
    50  		} else if n, err := dest.Write(b); err != nil {
    51  			return fmt.Errorf("cannot write [bytes] content: %w", err)
    52  		} else if n < length {
    53  			return errors.New("not enough capacity to write [bytes] content")
    54  		}
    55  	}
    56  	return nil
    57  }
    58  
    59  func LengthOfBytes(b []byte) int {
    60  	return LengthOfInt + len(b)
    61  }