list.go 1.5 KB

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