list.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 "google.golang.org/protobuf/reflect/protoreflect"
  8. )
  9. // ListOf returns a protoreflect.List view of p, which must be a *[]T.
  10. // If p is nil, this returns an empty, read-only list.
  11. func ListOf(p interface{}, c Converter) interface {
  12. pref.List
  13. Unwrapper
  14. } {
  15. // TODO: Validate that p is a *[]T?
  16. rv := reflect.ValueOf(p)
  17. return &listReflect{rv, c}
  18. }
  19. type listReflect struct {
  20. v reflect.Value // *[]T
  21. conv Converter
  22. }
  23. func (ls *listReflect) Len() int {
  24. if ls.v.IsNil() {
  25. return 0
  26. }
  27. return ls.v.Elem().Len()
  28. }
  29. func (ls *listReflect) Get(i int) pref.Value {
  30. return ls.conv.PBValueOf(ls.v.Elem().Index(i))
  31. }
  32. func (ls *listReflect) Set(i int, v pref.Value) {
  33. ls.v.Elem().Index(i).Set(ls.conv.GoValueOf(v))
  34. }
  35. func (ls *listReflect) Append(v pref.Value) {
  36. ls.v.Elem().Set(reflect.Append(ls.v.Elem(), ls.conv.GoValueOf(v)))
  37. }
  38. func (ls *listReflect) Truncate(i int) {
  39. ls.v.Elem().Set(ls.v.Elem().Slice(0, i))
  40. }
  41. func (ls *listReflect) NewMessage() pref.Message {
  42. return ls.conv.NewMessage()
  43. }
  44. func (ls *listReflect) ProtoUnwrap() interface{} {
  45. return ls.v.Interface()
  46. }