sslobodr | d046be8 | 2019-01-16 10:02:22 -0500 | [diff] [blame] | 1 | /* |
| 2 | Copyright 2015 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 fields |
| 18 | |
| 19 | import ( |
| 20 | "sort" |
| 21 | "strings" |
| 22 | ) |
| 23 | |
| 24 | // Fields allows you to present fields independently from their storage. |
| 25 | type Fields interface { |
| 26 | // Has returns whether the provided field exists. |
| 27 | Has(field string) (exists bool) |
| 28 | |
| 29 | // Get returns the value for the provided field. |
| 30 | Get(field string) (value string) |
| 31 | } |
| 32 | |
| 33 | // Set is a map of field:value. It implements Fields. |
| 34 | type Set map[string]string |
| 35 | |
| 36 | // String returns all fields listed as a human readable string. |
| 37 | // Conveniently, exactly the format that ParseSelector takes. |
| 38 | func (ls Set) String() string { |
| 39 | selector := make([]string, 0, len(ls)) |
| 40 | for key, value := range ls { |
| 41 | selector = append(selector, key+"="+value) |
| 42 | } |
| 43 | // Sort for determinism. |
| 44 | sort.StringSlice(selector).Sort() |
| 45 | return strings.Join(selector, ",") |
| 46 | } |
| 47 | |
| 48 | // Has returns whether the provided field exists in the map. |
| 49 | func (ls Set) Has(field string) bool { |
| 50 | _, exists := ls[field] |
| 51 | return exists |
| 52 | } |
| 53 | |
| 54 | // Get returns the value in the map for the provided field. |
| 55 | func (ls Set) Get(field string) string { |
| 56 | return ls[field] |
| 57 | } |
| 58 | |
| 59 | // AsSelector converts fields into a selectors. |
| 60 | func (ls Set) AsSelector() Selector { |
| 61 | return SelectorFromSet(ls) |
| 62 | } |