cosmossdk.io/client/v2@v2.0.0-beta.1/autocli/flag/maps/generic.go (about)

     1  package maps
     2  
     3  import (
     4  	"strings"
     5  
     6  	"github.com/cockroachdb/errors"
     7  )
     8  
     9  type genericMapValueOptions[K comparable, V any] struct {
    10  	keyParser   func(string) (K, error)
    11  	valueParser func(string) (V, error)
    12  	genericType string
    13  }
    14  
    15  type genericMapValue[K comparable, V any] struct {
    16  	value   *map[K]V
    17  	changed bool
    18  	Options genericMapValueOptions[K, V]
    19  }
    20  
    21  func newGenericMapValue[K comparable, V any](val map[K]V, p *map[K]V) *genericMapValue[K, V] {
    22  	ssv := new(genericMapValue[K, V])
    23  	ssv.value = p
    24  	*ssv.value = val
    25  	return ssv
    26  }
    27  
    28  func (gm *genericMapValue[K, V]) Set(val string) error {
    29  	ss := strings.Split(val, ",")
    30  	out := make(map[K]V, len(ss))
    31  	for _, pair := range ss {
    32  		kv := strings.SplitN(pair, "=", 2)
    33  		if len(kv) != 2 {
    34  			return errors.Errorf("%s must be formatted as key=value", pair)
    35  		}
    36  		key, err := gm.Options.keyParser(kv[0])
    37  		if err != nil {
    38  			return err
    39  		}
    40  		out[key], err = gm.Options.valueParser(kv[1])
    41  		if err != nil {
    42  			return err
    43  		}
    44  	}
    45  	if !gm.changed {
    46  		*gm.value = out
    47  	} else {
    48  		for k, v := range out {
    49  			(*gm.value)[k] = v
    50  		}
    51  	}
    52  	gm.changed = true
    53  	return nil
    54  }
    55  
    56  func (gm *genericMapValue[K, V]) Type() string {
    57  	return gm.Options.genericType
    58  }
    59  
    60  func (gm *genericMapValue[K, V]) String() string {
    61  	return ""
    62  }