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

     1  package validator
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  	"unicode/utf8"
     7  )
     8  
     9  type StrLenMode int
    10  
    11  const (
    12  	STR_LEN_MODE__LENGTH StrLenMode = iota
    13  	STR_LEN_MODE__RUNE_COUNT
    14  )
    15  
    16  var StrLenModes = map[StrLenMode]func(s string) uint64{
    17  	STR_LEN_MODE__LENGTH:     func(s string) uint64 { return uint64(len(s)) },
    18  	STR_LEN_MODE__RUNE_COUNT: func(s string) uint64 { return uint64(utf8.RuneCount([]byte(s))) },
    19  }
    20  
    21  func ParseStrLenMode(s string) (StrLenMode, error) {
    22  	switch strings.ToLower(s) {
    23  	case "rune_count":
    24  		return STR_LEN_MODE__RUNE_COUNT, nil
    25  	case "length", "":
    26  		return STR_LEN_MODE__LENGTH, nil
    27  	default:
    28  		return STR_LEN_MODE__LENGTH, fmt.Errorf("unsupported string length mode")
    29  	}
    30  }
    31  
    32  func (m StrLenMode) String() string {
    33  	switch m {
    34  	case STR_LEN_MODE__RUNE_COUNT:
    35  		return "rune_count"
    36  	default:
    37  		return "length"
    38  	}
    39  }
    40  
    41  func StringRuleParam(r *Rule) (mode StrLenMode, err error) {
    42  	if r.Params != nil {
    43  		if len(r.Params) != 1 {
    44  			err = fmt.Errorf(
    45  				"string should only 1 parameter, but got %d",
    46  				len(r.Params),
    47  			)
    48  			return
    49  		}
    50  		mode, err = ParseStrLenMode(string(r.Params[0].Bytes()))
    51  		return
    52  	}
    53  	if r.Name == "char" {
    54  		return STR_LEN_MODE__RUNE_COUNT, nil
    55  	}
    56  	return STR_LEN_MODE__LENGTH, nil
    57  }
    58  
    59  func StringRuleValues(r *Rule) map[string]string {
    60  	values := r.ComputedValues()
    61  	if values == nil {
    62  		return nil
    63  	}
    64  	enums := map[string]string{}
    65  	for _, v := range values {
    66  		str := string(v.Bytes())
    67  		enums[str] = str
    68  	}
    69  	return enums
    70  }