blob: 4c1a78d8341849696c56cef2c2d800c2ab137269 [file] [log] [blame]
Joe Tsai88bc5a72018-11-05 11:42:22 -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 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
19type vectorReflect struct {
20 v reflect.Value // addressable []T
21 conv Converter
22}
23
24func (vs vectorReflect) Len() int {
25 return vs.v.Len()
26}
27func (vs vectorReflect) Get(i int) pref.Value {
28 return vs.conv.PBValueOf(vs.v.Index(i))
29}
30func (vs vectorReflect) Set(i int, v pref.Value) {
31 vs.v.Index(i).Set(vs.conv.GoValueOf(v))
32}
33func (vs vectorReflect) Append(v pref.Value) {
34 vs.v.Set(reflect.Append(vs.v, vs.conv.GoValueOf(v)))
35}
36func (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}
46func (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}
52func (vs vectorReflect) Truncate(i int) {
53 vs.v.Set(vs.v.Slice(0, i))
54}
55func (vs vectorReflect) Unwrap() interface{} {
56 return vs.v.Interface()
57}
58func (vs vectorReflect) ProtoMutable() {}
59
60var (
61 _ pref.Vector = vectorReflect{}
62 _ Unwrapper = vectorReflect{}
63)