github.com/datastax/go-cassandra-native-protocol@v0.0.0-20220706104457-5e8aad05cf90/datatype/custom.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  // Custom is a data type that represents a CQL custom type.
    25  // +k8s:deepcopy-gen=true
    26  // +k8s:deepcopy-gen:interfaces=github.com/datastax/go-cassandra-native-protocol/datatype.DataType
    27  type Custom struct {
    28  	ClassName string
    29  }
    30  
    31  func NewCustom(className string) *Custom {
    32  	return &Custom{ClassName: className}
    33  }
    34  
    35  func (t *Custom) Code() primitive.DataTypeCode {
    36  	return primitive.DataTypeCodeCustom
    37  }
    38  
    39  func (t *Custom) String() string {
    40  	return t.AsCql()
    41  }
    42  
    43  func (t *Custom) AsCql() string {
    44  	return fmt.Sprintf("'%v'", t.ClassName)
    45  }
    46  
    47  func writeCustomType(t DataType, dest io.Writer, _ primitive.ProtocolVersion) (err error) {
    48  	if customType, ok := t.(*Custom); !ok {
    49  		return fmt.Errorf("expected *Custom, got %T", t)
    50  	} else if err = primitive.WriteString(customType.ClassName, dest); err != nil {
    51  		return fmt.Errorf("cannot write custom type class name: %w", err)
    52  	}
    53  	return nil
    54  }
    55  
    56  func lengthOfCustomType(t DataType, _ primitive.ProtocolVersion) (length int, err error) {
    57  	if customType, ok := t.(*Custom); !ok {
    58  		return -1, fmt.Errorf("expected *Custom, got %T", t)
    59  	} else {
    60  		length += primitive.LengthOfString(customType.ClassName)
    61  	}
    62  	return length, nil
    63  }
    64  
    65  func readCustomType(source io.Reader, _ primitive.ProtocolVersion) (t DataType, err error) {
    66  	customType := &Custom{}
    67  	if customType.ClassName, err = primitive.ReadString(source); err != nil {
    68  		return nil, fmt.Errorf("cannot read custom type class name: %w", err)
    69  	}
    70  	return customType, nil
    71  }