github.com/datastax/go-cassandra-native-protocol@v0.0.0-20220706104457-5e8aad05cf90/primitive/streamid.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  	"fmt"
    19  	"io"
    20  	"math"
    21  )
    22  
    23  // ReadStreamId reads a stream id from the given source, using the given version to determine if the stream id
    24  // is a 16-bit integer (versions 3+) or an 8-bit integer (versions 1 and 2).
    25  func ReadStreamId(source io.Reader, version ProtocolVersion) (int16, error) {
    26  	if version >= ProtocolVersion3 {
    27  		id, err := ReadShort(source)
    28  		return int16(id), err
    29  	} else {
    30  		id, err := ReadByte(source)
    31  		return int16(int8(id)), err
    32  	}
    33  }
    34  
    35  // WriteStreamId writes the given stream id to the given destination, using the given version to determine if the
    36  // stream id is a 16-bit integer (versions 3+) or an 8-bit integer (versions 1 and 2).
    37  func WriteStreamId(streamId int16, dest io.Writer, version ProtocolVersion) error {
    38  	if version >= ProtocolVersion3 {
    39  		return WriteShort(uint16(streamId), dest)
    40  	} else if streamId > math.MaxInt8 || streamId < math.MinInt8 {
    41  		return fmt.Errorf("stream id out of range for %v: %v", version, streamId)
    42  	} else {
    43  		return WriteByte(uint8(streamId), dest)
    44  	}
    45  }