github.com/NVIDIA/aistore@v1.3.23-0.20240517131212-7df6609be51d/cmn/cos/setkvs.go (about) 1 // Package cos provides common low-level types and utilities for all aistore projects. 2 /* 3 * Copyright (c) 2018-2024, NVIDIA CORPORATION. All rights reserved. 4 */ 5 package cos 6 7 import ( 8 "reflect" 9 "sort" 10 "strings" 11 12 "github.com/NVIDIA/aistore/cmn/debug" 13 ) 14 15 type ( 16 StrSet map[string]struct{} 17 StrKVs map[string]string 18 ) 19 20 //////////// 21 // StrKVs // 22 //////////// 23 24 func NewStrKVs(l int) StrKVs { 25 return make(StrKVs, l) 26 } 27 28 func (kvs StrKVs) Compare(other StrKVs) bool { 29 if len(kvs) != len(other) { 30 return false 31 } else if len(kvs) > 0 { 32 return reflect.DeepEqual(kvs, other) 33 } 34 return true 35 } 36 37 func (kvs StrKVs) Keys() []string { 38 keys := make([]string, 0, len(kvs)) 39 for k := range kvs { 40 keys = append(keys, k) 41 } 42 return keys 43 } 44 45 func (kvs StrKVs) KeyFor(value string) (key string) { 46 for k, v := range kvs { 47 if v == value { 48 key = k 49 break 50 } 51 } 52 return 53 } 54 55 func (kvs StrKVs) Contains(key string) (ok bool) { 56 _, ok = kvs[key] 57 return 58 } 59 60 func (kvs StrKVs) ContainsAnyMatch(in []string) string { 61 for _, k := range in { 62 debug.Assert(k != "") 63 for kk := range kvs { 64 if strings.Contains(kk, k) { 65 return kk 66 } 67 } 68 } 69 return "" 70 } 71 72 func (kvs StrKVs) Delete(key string) { 73 delete(kvs, key) 74 } 75 76 //////////// 77 // StrSet // 78 //////////// 79 80 func NewStrSet(keys ...string) (ss StrSet) { 81 ss = make(StrSet, len(keys)) 82 ss.Add(keys...) 83 return 84 } 85 86 func (ss StrSet) String() string { 87 keys := ss.ToSlice() 88 sort.Strings(keys) 89 return strings.Join(keys, ",") 90 } 91 92 func (ss StrSet) ToSlice() []string { 93 keys := make([]string, len(ss)) 94 idx := 0 95 for key := range ss { 96 keys[idx] = key 97 idx++ 98 } 99 return keys 100 } 101 102 func (ss StrSet) Set(key string) { 103 ss[key] = struct{}{} 104 } 105 106 func (ss StrSet) Add(keys ...string) { 107 for _, key := range keys { 108 ss[key] = struct{}{} 109 } 110 } 111 112 func (ss StrSet) Contains(key string) (yes bool) { 113 _, yes = ss[key] 114 return 115 } 116 117 func (ss StrSet) Delete(key string) { 118 delete(ss, key) 119 } 120 121 func (ss StrSet) Intersection(other StrSet) StrSet { 122 result := make(StrSet) 123 for key := range ss { 124 if other.Contains(key) { 125 result.Set(key) 126 } 127 } 128 return result 129 } 130 131 func (ss StrSet) Clone() StrSet { 132 result := make(StrSet, len(ss)) 133 for k, v := range ss { 134 result[k] = v 135 } 136 return result 137 } 138 139 func (ss StrSet) All(xs ...string) bool { 140 for _, x := range xs { 141 if !ss.Contains(x) { 142 return false 143 } 144 } 145 return true 146 }