blob: dadb05f50f9475e6ebf267827ff2ec5867f3c2eb [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?
18 rv := reflect.ValueOf(p).Elem()
19 return listReflect{rv, c}
20}
21
22type listReflect struct {
23 v reflect.Value // addressable []T
24 conv Converter
25}
26
27func (ls listReflect) Len() int {
28 return ls.v.Len()
29}
30func (ls listReflect) Get(i int) pref.Value {
31 return ls.conv.PBValueOf(ls.v.Index(i))
32}
33func (ls listReflect) Set(i int, v pref.Value) {
34 ls.v.Index(i).Set(ls.conv.GoValueOf(v))
35}
36func (ls listReflect) Append(v pref.Value) {
37 ls.v.Set(reflect.Append(ls.v, ls.conv.GoValueOf(v)))
38}
39func (ls listReflect) Mutable(i int) pref.Mutable {
40 // Mutable is only valid for messages and panics for other kinds.
Joe Tsaif6d4a422018-11-19 14:26:06 -080041 return ls.conv.PBValueOf(ls.v.Index(i)).Message()
Joe Tsai4b7aff62018-11-14 14:05:19 -080042}
43func (ls listReflect) MutableAppend() pref.Mutable {
44 // MutableAppend is only valid for messages and panics for other kinds.
45 pv := pref.ValueOf(ls.conv.MessageType.New().ProtoReflect())
46 ls.v.Set(reflect.Append(ls.v, ls.conv.GoValueOf(pv)))
Joe Tsaif6d4a422018-11-19 14:26:06 -080047 return pv.Message()
Joe Tsai4b7aff62018-11-14 14:05:19 -080048}
49func (ls listReflect) Truncate(i int) {
50 ls.v.Set(ls.v.Slice(0, i))
51}
Joe Tsaiba0ef9a2018-11-29 14:54:05 -080052func (ls listReflect) ProtoUnwrap() interface{} {
Joe Tsai4b7aff62018-11-14 14:05:19 -080053 return ls.v.Addr().Interface()
54}
55func (ls listReflect) ProtoMutable() {}