github.com/Finschia/finschia-sdk@v0.48.1/x/params/types/table.go (about)

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