Matteo Scandolo | a428586 | 2020-12-01 18:10:10 -0800 | [diff] [blame] | 1 | /* |
| 2 | Copyright 2019 The Kubernetes Authors. |
| 3 | |
| 4 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | you may not use this file except in compliance with the License. |
| 6 | You may obtain a copy of the License at |
| 7 | |
| 8 | http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | Unless required by applicable law or agreed to in writing, software |
| 11 | distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | See the License for the specific language governing permissions and |
| 14 | limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package value |
| 18 | |
| 19 | import ( |
| 20 | "sort" |
| 21 | "strings" |
| 22 | ) |
| 23 | |
| 24 | // Field is an individual key-value pair. |
| 25 | type Field struct { |
| 26 | Name string |
| 27 | Value Value |
| 28 | } |
| 29 | |
| 30 | // FieldList is a list of key-value pairs. Each field is expected to |
| 31 | // have a different name. |
| 32 | type FieldList []Field |
| 33 | |
| 34 | // Sort sorts the field list by Name. |
| 35 | func (f FieldList) Sort() { |
| 36 | if len(f) < 2 { |
| 37 | return |
| 38 | } |
| 39 | if len(f) == 2 { |
| 40 | if f[1].Name < f[0].Name { |
| 41 | f[0], f[1] = f[1], f[0] |
| 42 | } |
| 43 | return |
| 44 | } |
| 45 | sort.SliceStable(f, func(i, j int) bool { |
| 46 | return f[i].Name < f[j].Name |
| 47 | }) |
| 48 | } |
| 49 | |
| 50 | // Less compares two lists lexically. |
| 51 | func (f FieldList) Less(rhs FieldList) bool { |
| 52 | return f.Compare(rhs) == -1 |
| 53 | } |
| 54 | |
| 55 | // Compare compares two lists lexically. The result will be 0 if f==rhs, -1 |
| 56 | // if f < rhs, and +1 if f > rhs. |
| 57 | func (f FieldList) Compare(rhs FieldList) int { |
| 58 | i := 0 |
| 59 | for { |
| 60 | if i >= len(f) && i >= len(rhs) { |
| 61 | // Maps are the same length and all items are equal. |
| 62 | return 0 |
| 63 | } |
| 64 | if i >= len(f) { |
| 65 | // F is shorter. |
| 66 | return -1 |
| 67 | } |
| 68 | if i >= len(rhs) { |
| 69 | // RHS is shorter. |
| 70 | return 1 |
| 71 | } |
| 72 | if c := strings.Compare(f[i].Name, rhs[i].Name); c != 0 { |
| 73 | return c |
| 74 | } |
| 75 | if c := Compare(f[i].Value, rhs[i].Value); c != 0 { |
| 76 | return c |
| 77 | } |
| 78 | // The items are equal; continue. |
| 79 | i++ |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | // Equals returns true if the two fieldslist are equals, false otherwise. |
| 84 | func (f FieldList) Equals(rhs FieldList) bool { |
| 85 | if len(f) != len(rhs) { |
| 86 | return false |
| 87 | } |
| 88 | for i := range f { |
| 89 | if f[i].Name != rhs[i].Name { |
| 90 | return false |
| 91 | } |
| 92 | if !Equals(f[i].Value, rhs[i].Value) { |
| 93 | return false |
| 94 | } |
| 95 | } |
| 96 | return true |
| 97 | } |