Joe Tsai | 4b7aff6 | 2018-11-14 14:05:19 -0800 | [diff] [blame] | 1 | // 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 | |
| 5 | package value |
| 6 | |
| 7 | import ( |
| 8 | "reflect" |
| 9 | |
| 10 | pref "github.com/golang/protobuf/v2/reflect/protoreflect" |
| 11 | ) |
| 12 | |
Joe Tsai | ba0ef9a | 2018-11-29 14:54:05 -0800 | [diff] [blame^] | 13 | func ListOf(p interface{}, c Converter) interface { |
| 14 | pref.List |
| 15 | Unwrapper |
| 16 | } { |
Joe Tsai | 4b7aff6 | 2018-11-14 14:05:19 -0800 | [diff] [blame] | 17 | // TODO: Validate that p is a *[]T? |
| 18 | rv := reflect.ValueOf(p).Elem() |
| 19 | return listReflect{rv, c} |
| 20 | } |
| 21 | |
| 22 | type listReflect struct { |
| 23 | v reflect.Value // addressable []T |
| 24 | conv Converter |
| 25 | } |
| 26 | |
| 27 | func (ls listReflect) Len() int { |
| 28 | return ls.v.Len() |
| 29 | } |
| 30 | func (ls listReflect) Get(i int) pref.Value { |
| 31 | return ls.conv.PBValueOf(ls.v.Index(i)) |
| 32 | } |
| 33 | func (ls listReflect) Set(i int, v pref.Value) { |
| 34 | ls.v.Index(i).Set(ls.conv.GoValueOf(v)) |
| 35 | } |
| 36 | func (ls listReflect) Append(v pref.Value) { |
| 37 | ls.v.Set(reflect.Append(ls.v, ls.conv.GoValueOf(v))) |
| 38 | } |
| 39 | func (ls listReflect) Mutable(i int) pref.Mutable { |
| 40 | // Mutable is only valid for messages and panics for other kinds. |
Joe Tsai | f6d4a42 | 2018-11-19 14:26:06 -0800 | [diff] [blame] | 41 | return ls.conv.PBValueOf(ls.v.Index(i)).Message() |
Joe Tsai | 4b7aff6 | 2018-11-14 14:05:19 -0800 | [diff] [blame] | 42 | } |
| 43 | func (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 Tsai | f6d4a42 | 2018-11-19 14:26:06 -0800 | [diff] [blame] | 47 | return pv.Message() |
Joe Tsai | 4b7aff6 | 2018-11-14 14:05:19 -0800 | [diff] [blame] | 48 | } |
| 49 | func (ls listReflect) Truncate(i int) { |
| 50 | ls.v.Set(ls.v.Slice(0, i)) |
| 51 | } |
Joe Tsai | ba0ef9a | 2018-11-29 14:54:05 -0800 | [diff] [blame^] | 52 | func (ls listReflect) ProtoUnwrap() interface{} { |
Joe Tsai | 4b7aff6 | 2018-11-14 14:05:19 -0800 | [diff] [blame] | 53 | return ls.v.Addr().Interface() |
| 54 | } |
| 55 | func (ls listReflect) ProtoMutable() {} |