github.com/datastax/go-cassandra-native-protocol@v0.0.0-20220706104457-5e8aad05cf90/primitive/short_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  // [short bytes]
    24  
    25  func ReadShortBytes(source io.Reader) ([]byte, error) {
    26  	if length, err := ReadShort(source); err != nil {
    27  		return nil, fmt.Errorf("cannot read [short 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 [short bytes] content: %w", err)
    36  		}
    37  		return decoded, nil
    38  	}
    39  }
    40  
    41  func WriteShortBytes(b []byte, dest io.Writer) error {
    42  	length := len(b)
    43  	if err := WriteShort(uint16(length), dest); err != nil {
    44  		return fmt.Errorf("cannot write [short bytes] length: %w", err)
    45  	} else if n, err := dest.Write(b); err != nil {
    46  		return fmt.Errorf("cannot write [short bytes] content: %w", err)
    47  	} else if n < length {
    48  		return errors.New("not enough capacity to write [short bytes] content")
    49  	}
    50  	return nil
    51  }
    52  
    53  func LengthOfShortBytes(b []byte) int {
    54  	return LengthOfShort + len(b)
    55  }