github.com/datastax/go-cassandra-native-protocol@v0.0.0-20220706104457-5e8aad05cf90/datatype/set.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 datatype
    16  
    17  import (
    18  	"fmt"
    19  	"io"
    20  
    21  	"github.com/datastax/go-cassandra-native-protocol/primitive"
    22  )
    23  
    24  // Set is a data type that represents a CQL set type.
    25  // +k8s:deepcopy-gen=true
    26  // +k8s:deepcopy-gen:interfaces=github.com/datastax/go-cassandra-native-protocol/datatype.DataType
    27  type Set struct {
    28  	ElementType DataType
    29  }
    30  
    31  func (t *Set) Code() primitive.DataTypeCode {
    32  	return primitive.DataTypeCodeSet
    33  }
    34  
    35  func (t *Set) String() string {
    36  	return t.AsCql()
    37  }
    38  
    39  func (t *Set) AsCql() string {
    40  	return fmt.Sprintf("set<%v>", t.ElementType.AsCql())
    41  }
    42  
    43  func NewSet(elementType DataType) *Set {
    44  	return &Set{ElementType: elementType}
    45  }
    46  
    47  func writeSetType(t DataType, dest io.Writer, version primitive.ProtocolVersion) (err error) {
    48  	if setType, ok := t.(*Set); !ok {
    49  		return fmt.Errorf("expected *Set, got %T", t)
    50  	} else if err = WriteDataType(setType.ElementType, dest, version); err != nil {
    51  		return fmt.Errorf("cannot write set element type: %w", err)
    52  	}
    53  	return nil
    54  }
    55  
    56  func lengthOfSetType(t DataType, version primitive.ProtocolVersion) (length int, err error) {
    57  	if setType, ok := t.(*Set); !ok {
    58  		return -1, fmt.Errorf("expected *Set, got %T", t)
    59  	} else if elementLength, err := LengthOfDataType(setType.ElementType, version); err != nil {
    60  		return -1, fmt.Errorf("cannot compute length of set element type: %w", err)
    61  	} else {
    62  		length += elementLength
    63  	}
    64  	return length, nil
    65  }
    66  
    67  func readSetType(source io.Reader, version primitive.ProtocolVersion) (decoded DataType, err error) {
    68  	setType := &Set{}
    69  	if setType.ElementType, err = ReadDataType(source, version); err != nil {
    70  		return nil, fmt.Errorf("cannot read set element type: %w", err)
    71  	}
    72  	return setType, nil
    73  }