github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/validator/validator_helper_map.go (about)

     1  package validator
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/machinefi/w3bstream/pkg/depends/kit/validator/rules"
     8  )
     9  
    10  func MapRuleParam(ctx context.Context, r *Rule) (key, elem Validator, err error) {
    11  	if r.Params == nil {
    12  		return
    13  	}
    14  
    15  	if len(r.Params) != 2 {
    16  		err = fmt.Errorf(
    17  			"map should only 2 parameter, but got %d", len(r.Params),
    18  		)
    19  		return
    20  	}
    21  
    22  	compiler := FactoryFromContext(ctx)
    23  
    24  	for i, param := range r.Params {
    25  		switch rule := param.(type) {
    26  		case *rules.Rule:
    27  			switch i {
    28  			case 0:
    29  				key, err = compiler.Compile(ctx, rule.RAW, r.Type.Key())
    30  				if err != nil {
    31  					err = fmt.Errorf("map key %s", err)
    32  					return
    33  				}
    34  			case 1:
    35  				elem, err = compiler.Compile(ctx, rule.RAW, r.Type.Elem())
    36  				if err != nil {
    37  					err = fmt.Errorf("map elem %s", err)
    38  					return
    39  				}
    40  			}
    41  		case *rules.Lit:
    42  			raw := rule.Bytes()
    43  			if len(raw) > 0 {
    44  				err = fmt.Errorf("map parameter should be a valid rule")
    45  				return
    46  			}
    47  			elem, err = compiler.Compile(ctx, raw, r.Type.Elem())
    48  			if err != nil {
    49  				err = fmt.Errorf("map elem %s", err)
    50  				return
    51  			}
    52  		}
    53  	}
    54  	return
    55  }