blob: ba82b30ae10f48095999f1ad019c75fbc7e46ac9 [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
13func ListOf(p interface{}, c Converter) pref.List {
14 // TODO: Validate that p is a *[]T?
15 rv := reflect.ValueOf(p).Elem()
16 return listReflect{rv, c}
17}
18
19type listReflect struct {
20 v reflect.Value // addressable []T
21 conv Converter
22}
23
24func (ls listReflect) Len() int {
25 return ls.v.Len()
26}
27func (ls listReflect) Get(i int) pref.Value {
28 return ls.conv.PBValueOf(ls.v.Index(i))
29}
30func (ls listReflect) Set(i int, v pref.Value) {
31 ls.v.Index(i).Set(ls.conv.GoValueOf(v))
32}
33func (ls listReflect) Append(v pref.Value) {
34 ls.v.Set(reflect.Append(ls.v, ls.conv.GoValueOf(v)))
35}
36func (ls listReflect) Mutable(i int) pref.Mutable {
37 // Mutable is only valid for messages and panics for other kinds.
Joe Tsaif6d4a422018-11-19 14:26:06 -080038 return ls.conv.PBValueOf(ls.v.Index(i)).Message()
Joe Tsai4b7aff62018-11-14 14:05:19 -080039}
40func (ls listReflect) MutableAppend() pref.Mutable {
41 // MutableAppend is only valid for messages and panics for other kinds.
42 pv := pref.ValueOf(ls.conv.MessageType.New().ProtoReflect())
43 ls.v.Set(reflect.Append(ls.v, ls.conv.GoValueOf(pv)))
Joe Tsaif6d4a422018-11-19 14:26:06 -080044 return pv.Message()
Joe Tsai4b7aff62018-11-14 14:05:19 -080045}
46func (ls listReflect) Truncate(i int) {
47 ls.v.Set(ls.v.Slice(0, i))
48}
49func (ls listReflect) Unwrap() interface{} {
50 return ls.v.Addr().Interface()
51}
52func (ls listReflect) ProtoMutable() {}
53
54var (
55 _ pref.List = listReflect{}
56 _ Unwrapper = listReflect{}
57)