fields.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. // Sort sorts the field list by Name.
  27. func (f FieldList) Sort() {
  28. if len(f) < 2 {
  29. return
  30. }
  31. if len(f) == 2 {
  32. if f[1].Name < f[0].Name {
  33. f[0], f[1] = f[1], f[0]
  34. }
  35. return
  36. }
  37. sort.SliceStable(f, func(i, j int) bool {
  38. return f[i].Name < f[j].Name
  39. })
  40. }
  41. // Less compares two lists lexically.
  42. func (f FieldList) Less(rhs FieldList) bool {
  43. return f.Compare(rhs) == -1
  44. }
  45. // Compare compares two lists lexically. The result will be 0 if f==rhs, -1
  46. // if f < rhs, and +1 if f > rhs.
  47. func (f FieldList) Compare(rhs FieldList) int {
  48. i := 0
  49. for {
  50. if i >= len(f) && i >= len(rhs) {
  51. // Maps are the same length and all items are equal.
  52. return 0
  53. }
  54. if i >= len(f) {
  55. // F is shorter.
  56. return -1
  57. }
  58. if i >= len(rhs) {
  59. // RHS is shorter.
  60. return 1
  61. }
  62. if c := strings.Compare(f[i].Name, rhs[i].Name); c != 0 {
  63. return c
  64. }
  65. if c := Compare(f[i].Value, rhs[i].Value); c != 0 {
  66. return c
  67. }
  68. // The items are equal; continue.
  69. i++
  70. }
  71. }
  72. // Equals returns true if the two fieldslist are equals, false otherwise.
  73. func (f FieldList) Equals(rhs FieldList) bool {
  74. if len(f) != len(rhs) {
  75. return false
  76. }
  77. for i := range f {
  78. if f[i].Name != rhs[i].Name {
  79. return false
  80. }
  81. if !Equals(f[i].Value, rhs[i].Value) {
  82. return false
  83. }
  84. }
  85. return true
  86. }