github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/framework/utils/kv.go (about)

     1  // Copyright 2020 beego-dev
     2  //
     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  //
     7  // http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package utils
    16  
    17  type KV interface {
    18  	GetKey() interface{}
    19  	GetValue() interface{}
    20  }
    21  
    22  // SimpleKV is common structure to store key-value pairs.
    23  // When you need something like Pair, you can use this
    24  type SimpleKV struct {
    25  	Key   interface{}
    26  	Value interface{}
    27  }
    28  
    29  var _ KV = new(SimpleKV)
    30  
    31  func (s *SimpleKV) GetKey() interface{} {
    32  	return s.Key
    33  }
    34  
    35  func (s *SimpleKV) GetValue() interface{} {
    36  	return s.Value
    37  }
    38  
    39  // KVs interface
    40  type KVs interface {
    41  	GetValueOr(key interface{}, defValue interface{}) interface{}
    42  	Contains(key interface{}) bool
    43  	IfContains(key interface{}, action func(value interface{})) KVs
    44  }
    45  
    46  // SimpleKVs will store SimpleKV collection as map
    47  type SimpleKVs struct {
    48  	kvs map[interface{}]interface{}
    49  }
    50  
    51  var _ KVs = new(SimpleKVs)
    52  
    53  // GetValueOr returns the value for a given key, if non-existent
    54  // it returns defValue
    55  func (kvs *SimpleKVs) GetValueOr(key interface{}, defValue interface{}) interface{} {
    56  	v, ok := kvs.kvs[key]
    57  	if ok {
    58  		return v
    59  	}
    60  	return defValue
    61  }
    62  
    63  // Contains checks if a key exists
    64  func (kvs *SimpleKVs) Contains(key interface{}) bool {
    65  	_, ok := kvs.kvs[key]
    66  	return ok
    67  }
    68  
    69  // IfContains invokes the action on a key if it exists
    70  func (kvs *SimpleKVs) IfContains(key interface{}, action func(value interface{})) KVs {
    71  	v, ok := kvs.kvs[key]
    72  	if ok {
    73  		action(v)
    74  	}
    75  	return kvs
    76  }
    77  
    78  // NewKVs creates the *KVs instance
    79  func NewKVs(kvs ...KV) KVs {
    80  	res := &SimpleKVs{
    81  		kvs: make(map[interface{}]interface{}, len(kvs)),
    82  	}
    83  	for _, kv := range kvs {
    84  		res.kvs[kv.GetKey()] = kv.GetValue()
    85  	}
    86  	return res
    87  }