fields.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. "sort"
  16. "strings"
  17. )
  18. // Field is an individual key-value pair.
  19. type Field struct {
  20. Name string
  21. Value Value
  22. }
  23. // FieldList is a list of key-value pairs. Each field is expected to
  24. // have a different name.
  25. type FieldList []Field
  26. // Copy returns a copy of the FieldList.
  27. // Values are not copied.
  28. func (f FieldList) Copy() FieldList {
  29. c := make(FieldList, len(f))
  30. copy(c, f)
  31. return c
  32. }
  33. // Sort sorts the field list by Name.
  34. func (f FieldList) Sort() {
  35. if len(f) < 2 {
  36. return
  37. }
  38. if len(f) == 2 {
  39. if f[1].Name < f[0].Name {
  40. f[0], f[1] = f[1], f[0]
  41. }
  42. return
  43. }
  44. sort.SliceStable(f, func(i, j int) bool {
  45. return f[i].Name < f[j].Name
  46. })
  47. }
  48. // Less compares two lists lexically.
  49. func (f FieldList) Less(rhs FieldList) bool {
  50. return f.Compare(rhs) == -1
  51. }
  52. // Compare compares two lists lexically. The result will be 0 if f==rhs, -1
  53. // if f < rhs, and +1 if f > rhs.
  54. func (f FieldList) Compare(rhs FieldList) int {
  55. i := 0
  56. for {
  57. if i >= len(f) && i >= len(rhs) {
  58. // Maps are the same length and all items are equal.
  59. return 0
  60. }
  61. if i >= len(f) {
  62. // F is shorter.
  63. return -1
  64. }
  65. if i >= len(rhs) {
  66. // RHS is shorter.
  67. return 1
  68. }
  69. if c := strings.Compare(f[i].Name, rhs[i].Name); c != 0 {
  70. return c
  71. }
  72. if c := Compare(f[i].Value, rhs[i].Value); c != 0 {
  73. return c
  74. }
  75. // The items are equal; continue.
  76. i++
  77. }
  78. }
  79. // Equals returns true if the two fieldslist are equals, false otherwise.
  80. func (f FieldList) Equals(rhs FieldList) bool {
  81. if len(f) != len(rhs) {
  82. return false
  83. }
  84. for i := range f {
  85. if f[i].Name != rhs[i].Name {
  86. return false
  87. }
  88. if !Equals(f[i].Value, rhs[i].Value) {
  89. return false
  90. }
  91. }
  92. return true
  93. }