go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/starlark/starlarkproto/values_list.go (about)

     1  // Copyright 2019 The LUCI Authors.
     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 starlarkproto
    16  
    17  import (
    18  	"fmt"
    19  
    20  	"go.starlark.net/starlark"
    21  
    22  	"google.golang.org/protobuf/reflect/protoreflect"
    23  
    24  	"go.chromium.org/luci/starlark/typed"
    25  )
    26  
    27  // newStarlarkList returns a new typed.List of an appropriate type.
    28  func newStarlarkList(l *Loader, fd protoreflect.FieldDescriptor) *typed.List {
    29  	list, _ := typed.NewList(converter(l, fd), nil)
    30  	return list
    31  }
    32  
    33  // toStarlarkList does protoreflect.List => typed.List conversion.
    34  //
    35  // Panics if type of 'list' (or some of its items) doesn't match 'fd'.
    36  func toStarlarkList(l *Loader, fd protoreflect.FieldDescriptor, list protoreflect.List) *typed.List {
    37  	vals := make([]starlark.Value, list.Len())
    38  	for i := 0; i < list.Len(); i++ {
    39  		vals[i] = toStarlarkSingular(l, fd, list.Get(i))
    40  	}
    41  	tl, err := typed.NewList(converter(l, fd), vals)
    42  	if err != nil {
    43  		panic(fmt.Errorf("internal error: unexpectedly wrong protoreflect.List %s", list))
    44  	}
    45  	return tl
    46  }
    47  
    48  // assignProtoList does m.fd = list, where fd is a repeated field.
    49  //
    50  // Assumes type checks have been done already (this is responsibility of
    51  // prepareRHS). Panics on type mismatch.
    52  func assignProtoList(m protoreflect.Message, fd protoreflect.FieldDescriptor, list *typed.List) {
    53  	protoList := m.Mutable(fd).List()
    54  	if protoList.Len() != 0 {
    55  		panic(fmt.Errorf("internal error: the proto list is not empty"))
    56  	}
    57  	for i := 0; i < list.Len(); i++ {
    58  		protoList.Append(toProtoSingular(fd, list.Index(i)))
    59  	}
    60  }