blob: 37f9b55c553a756199ef6669c59907bfe74f4e6e [file] [log] [blame]
Joe Tsai4b7aff62018-11-14 14:05:19 -08001// Copyright 2018 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package value
6
7import (
8 "reflect"
9
10 pref "github.com/golang/protobuf/v2/reflect/protoreflect"
11)
12
Joe Tsaiba0ef9a2018-11-29 14:54:05 -080013func ListOf(p interface{}, c Converter) interface {
14 pref.List
15 Unwrapper
16} {
Joe Tsai4b7aff62018-11-14 14:05:19 -080017 // TODO: Validate that p is a *[]T?
Joe Tsai6cf80c42018-12-01 04:57:09 -080018 rv := reflect.ValueOf(p)
Joe Tsai4b7aff62018-11-14 14:05:19 -080019 return listReflect{rv, c}
20}
21
22type listReflect struct {
Joe Tsai6cf80c42018-12-01 04:57:09 -080023 v reflect.Value // *[]T
Joe Tsai4b7aff62018-11-14 14:05:19 -080024 conv Converter
25}
26
27func (ls listReflect) Len() int {
Joe Tsai6cf80c42018-12-01 04:57:09 -080028 if ls.v.IsNil() {
29 return 0
30 }
31 return ls.v.Elem().Len()
Joe Tsai4b7aff62018-11-14 14:05:19 -080032}
33func (ls listReflect) Get(i int) pref.Value {
Joe Tsai6cf80c42018-12-01 04:57:09 -080034 return ls.conv.PBValueOf(ls.v.Elem().Index(i))
Joe Tsai4b7aff62018-11-14 14:05:19 -080035}
36func (ls listReflect) Set(i int, v pref.Value) {
Joe Tsai6cf80c42018-12-01 04:57:09 -080037 ls.v.Elem().Index(i).Set(ls.conv.GoValueOf(v))
Joe Tsai4b7aff62018-11-14 14:05:19 -080038}
39func (ls listReflect) Append(v pref.Value) {
Joe Tsai6cf80c42018-12-01 04:57:09 -080040 ls.v.Elem().Set(reflect.Append(ls.v.Elem(), ls.conv.GoValueOf(v)))
Joe Tsai4b7aff62018-11-14 14:05:19 -080041}
Joe Tsai4b7aff62018-11-14 14:05:19 -080042func (ls listReflect) Truncate(i int) {
Joe Tsai6cf80c42018-12-01 04:57:09 -080043 ls.v.Elem().Set(ls.v.Elem().Slice(0, i))
Joe Tsai4b7aff62018-11-14 14:05:19 -080044}
Joe Tsai3bc7d6f2019-01-09 02:57:13 -080045func (ls listReflect) NewMessage() pref.Message {
Damien Neil97e7f572018-12-07 14:28:33 -080046 return ls.conv.MessageType.New()
47}
Joe Tsaiba0ef9a2018-11-29 14:54:05 -080048func (ls listReflect) ProtoUnwrap() interface{} {
Joe Tsai6cf80c42018-12-01 04:57:09 -080049 return ls.v.Interface()
Joe Tsai4b7aff62018-11-14 14:05:19 -080050}