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