vector.go 1.7 KB

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