github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/validator/validator_helper_slice.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 SliceElementRule(ctx context.Context, r *Rule) (Validator, error) { 11 raw := []byte("") 12 13 if r.Params != nil { 14 if len(r.Params) != 1 { 15 return nil, fmt.Errorf( 16 "slice should only 1 parameter, but got %d", len(r.Params), 17 ) 18 } 19 rule, ok := r.Params[0].(*rules.Rule) 20 if !ok { 21 return nil, fmt.Errorf("slice parameter should be a valid rule") 22 } 23 raw = rule.RAW 24 } 25 26 compiler := FactoryFromContext(ctx) 27 28 v, err := compiler.Compile(ctx, raw, r.Type.Elem(), nil) 29 if err != nil { 30 return nil, fmt.Errorf("slice elem %s", err) 31 } 32 return v, nil 33 } 34 35 func RangeFromUint(min uint64, max *uint64) []*rules.Lit { 36 ranges := make([]*rules.Lit, 2) 37 38 if min == 0 && max == nil { 39 return nil 40 } 41 42 ranges[0] = rules.NewLiteral([]byte(fmt.Sprintf("%d", min))) 43 44 if max != nil { 45 if min == *max { 46 return []*rules.Lit{ranges[0]} 47 } 48 ranges[1] = rules.NewLiteral([]byte(fmt.Sprintf("%d", *max))) 49 } 50 51 return ranges 52 }