listreflect.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. Copyright 2019 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package value
  14. import (
  15. "reflect"
  16. )
  17. type listReflect struct {
  18. Value reflect.Value
  19. }
  20. func (r listReflect) Length() int {
  21. val := r.Value
  22. return val.Len()
  23. }
  24. func (r listReflect) At(i int) Value {
  25. val := r.Value
  26. return mustWrapValueReflect(val.Index(i), nil, nil)
  27. }
  28. func (r listReflect) AtUsing(a Allocator, i int) Value {
  29. val := r.Value
  30. return a.allocValueReflect().mustReuse(val.Index(i), nil, nil, nil)
  31. }
  32. func (r listReflect) Unstructured() interface{} {
  33. l := r.Length()
  34. result := make([]interface{}, l)
  35. for i := 0; i < l; i++ {
  36. result[i] = r.At(i).Unstructured()
  37. }
  38. return result
  39. }
  40. func (r listReflect) Range() ListRange {
  41. return r.RangeUsing(HeapAllocator)
  42. }
  43. func (r listReflect) RangeUsing(a Allocator) ListRange {
  44. length := r.Value.Len()
  45. if length == 0 {
  46. return EmptyRange
  47. }
  48. rr := a.allocListReflectRange()
  49. rr.list = r.Value
  50. rr.i = -1
  51. rr.entry = TypeReflectEntryOf(r.Value.Type().Elem())
  52. return rr
  53. }
  54. func (r listReflect) Equals(other List) bool {
  55. return r.EqualsUsing(HeapAllocator, other)
  56. }
  57. func (r listReflect) EqualsUsing(a Allocator, other List) bool {
  58. if otherReflectList, ok := other.(*listReflect); ok {
  59. return reflect.DeepEqual(r.Value.Interface(), otherReflectList.Value.Interface())
  60. }
  61. return ListEqualsUsing(a, &r, other)
  62. }
  63. type listReflectRange struct {
  64. list reflect.Value
  65. vr *valueReflect
  66. i int
  67. entry *TypeReflectCacheEntry
  68. }
  69. func (r *listReflectRange) Next() bool {
  70. r.i += 1
  71. return r.i < r.list.Len()
  72. }
  73. func (r *listReflectRange) Item() (index int, value Value) {
  74. if r.i < 0 {
  75. panic("Item() called before first calling Next()")
  76. }
  77. if r.i >= r.list.Len() {
  78. panic("Item() called on ListRange with no more items")
  79. }
  80. v := r.list.Index(r.i)
  81. return r.i, r.vr.mustReuse(v, r.entry, nil, nil)
  82. }