list.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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) interface {
  10. pref.List
  11. Unwrapper
  12. } {
  13. // TODO: Validate that p is a *[]T?
  14. rv := reflect.ValueOf(p)
  15. return listReflect{rv, c}
  16. }
  17. type listReflect struct {
  18. v reflect.Value // *[]T
  19. conv Converter
  20. }
  21. func (ls listReflect) Len() int {
  22. if ls.v.IsNil() {
  23. return 0
  24. }
  25. return ls.v.Elem().Len()
  26. }
  27. func (ls listReflect) Get(i int) pref.Value {
  28. return ls.conv.PBValueOf(ls.v.Elem().Index(i))
  29. }
  30. func (ls listReflect) Set(i int, v pref.Value) {
  31. ls.v.Elem().Index(i).Set(ls.conv.GoValueOf(v))
  32. }
  33. func (ls listReflect) Append(v pref.Value) {
  34. ls.v.Elem().Set(reflect.Append(ls.v.Elem(), ls.conv.GoValueOf(v)))
  35. }
  36. func (ls listReflect) Truncate(i int) {
  37. ls.v.Elem().Set(ls.v.Elem().Slice(0, i))
  38. }
  39. func (ls listReflect) NewMessage() pref.Message {
  40. return ls.conv.MessageType.New()
  41. }
  42. func (ls listReflect) ProtoUnwrap() interface{} {
  43. return ls.v.Interface()
  44. }