Joe Tsai | 88bc5a7 | 2018-11-05 11:42:22 -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 | |
| 13 | func VectorOf(p interface{}, c Converter) pref.Vector { |
| 14 | // TODO: Validate that p is a *[]T? |
| 15 | rv := reflect.ValueOf(p).Elem() |
| 16 | return vectorReflect{rv, c} |
| 17 | } |
| 18 | |
| 19 | type vectorReflect struct { |
| 20 | v reflect.Value // addressable []T |
| 21 | conv Converter |
| 22 | } |
| 23 | |
| 24 | func (vs vectorReflect) Len() int { |
| 25 | return vs.v.Len() |
| 26 | } |
| 27 | func (vs vectorReflect) Get(i int) pref.Value { |
| 28 | return vs.conv.PBValueOf(vs.v.Index(i)) |
| 29 | } |
| 30 | func (vs vectorReflect) Set(i int, v pref.Value) { |
| 31 | vs.v.Index(i).Set(vs.conv.GoValueOf(v)) |
| 32 | } |
| 33 | func (vs vectorReflect) Append(v pref.Value) { |
| 34 | vs.v.Set(reflect.Append(vs.v, vs.conv.GoValueOf(v))) |
| 35 | } |
| 36 | func (vs vectorReflect) Mutable(i int) pref.Mutable { |
| 37 | // Mutable is only valid for messages and panics for other kinds. |
| 38 | rv := vs.v.Index(i) |
| 39 | if rv.IsNil() { |
| 40 | // TODO: Is checking for nil proper behavior for custom messages? |
| 41 | pv := pref.ValueOf(vs.conv.NewMessage()) |
| 42 | rv.Set(vs.conv.GoValueOf(pv)) |
| 43 | } |
| 44 | return rv.Interface().(pref.Message) |
| 45 | } |
| 46 | func (vs vectorReflect) MutableAppend() pref.Mutable { |
| 47 | // MutableAppend is only valid for messages and panics for other kinds. |
| 48 | pv := pref.ValueOf(vs.conv.NewMessage()) |
| 49 | vs.v.Set(reflect.Append(vs.v, vs.conv.GoValueOf(pv))) |
| 50 | return vs.v.Index(vs.Len() - 1).Interface().(pref.Message) |
| 51 | } |
| 52 | func (vs vectorReflect) Truncate(i int) { |
| 53 | vs.v.Set(vs.v.Slice(0, i)) |
| 54 | } |
| 55 | func (vs vectorReflect) Unwrap() interface{} { |
| 56 | return vs.v.Interface() |
| 57 | } |
| 58 | func (vs vectorReflect) ProtoMutable() {} |
| 59 | |
| 60 | var ( |
| 61 | _ pref.Vector = vectorReflect{} |
| 62 | _ Unwrapper = vectorReflect{} |
| 63 | ) |