github.com/cosmos/cosmos-sdk@v0.50.10/x/params/types/table.go (about)

     1  package types
     2  
     3  import (
     4  	"reflect"
     5  
     6  	sdk "github.com/cosmos/cosmos-sdk/types"
     7  )
     8  
     9  type attribute struct {
    10  	ty  reflect.Type
    11  	vfn ValueValidatorFn
    12  }
    13  
    14  // KeyTable subspaces appropriate type for each parameter key
    15  type KeyTable struct {
    16  	m map[string]attribute
    17  }
    18  
    19  // IsOnePerModuleType implements depinject.OnePerModuleType
    20  func (KeyTable) IsOnePerModuleType() {}
    21  
    22  func NewKeyTable(pairs ...ParamSetPair) KeyTable {
    23  	keyTable := KeyTable{
    24  		m: make(map[string]attribute),
    25  	}
    26  
    27  	for _, psp := range pairs {
    28  		keyTable = keyTable.RegisterType(psp)
    29  	}
    30  
    31  	return keyTable
    32  }
    33  
    34  // RegisterType registers a single ParamSetPair (key-type pair) in a KeyTable.
    35  func (t KeyTable) RegisterType(psp ParamSetPair) KeyTable {
    36  	if len(psp.Key) == 0 {
    37  		panic("cannot register ParamSetPair with an parameter empty key")
    38  	}
    39  	if !sdk.IsAlphaNumeric(string(psp.Key)) {
    40  		panic("cannot register ParamSetPair with a non-alphanumeric parameter key")
    41  	}
    42  	if psp.ValidatorFn == nil {
    43  		panic("cannot register ParamSetPair without a value validation function")
    44  	}
    45  
    46  	keystr := string(psp.Key)
    47  	if _, ok := t.m[keystr]; ok {
    48  		panic("duplicate parameter key")
    49  	}
    50  
    51  	rty := reflect.TypeOf(psp.Value)
    52  
    53  	// indirect rty if it is a pointer
    54  	for rty.Kind() == reflect.Ptr {
    55  		rty = rty.Elem()
    56  	}
    57  
    58  	t.m[keystr] = attribute{
    59  		vfn: psp.ValidatorFn,
    60  		ty:  rty,
    61  	}
    62  
    63  	return t
    64  }
    65  
    66  // RegisterParamSet registers multiple ParamSetPairs from a ParamSet in a KeyTable.
    67  func (t KeyTable) RegisterParamSet(ps ParamSet) KeyTable {
    68  	for _, psp := range ps.ParamSetPairs() {
    69  		t = t.RegisterType(psp)
    70  	}
    71  	return t
    72  }
    73  
    74  func (t KeyTable) maxKeyLength() (res int) {
    75  	for k := range t.m {
    76  		l := len(k)
    77  		if l > res {
    78  			res = l
    79  		}
    80  	}
    81  
    82  	return
    83  }