github.com/zerosnake0/jzon@v0.0.9-0.20230801092939-1b135cb83f7f/struct_tag.go (about)

     1  package jzon
     2  
     3  import (
     4  	"strings"
     5  	"unicode"
     6  )
     7  
     8  /* see encoding/json
     9   * - some additional comments may be added
    10   * - some code may be slightly modified
    11   */
    12  
    13  // tagOptions is the string following a comma in a struct field's "json"
    14  // tag, or the empty string. It does not include the leading comma.
    15  type tagOptions string
    16  
    17  // parseTag splits a struct field's json tag into its name and
    18  // comma-separated options.
    19  func parseTag(tag string) (string, tagOptions) {
    20  	if idx := strings.Index(tag, ","); idx != -1 {
    21  		return tag[:idx], tagOptions(tag[idx+1:])
    22  	}
    23  	return tag, tagOptions("")
    24  }
    25  
    26  // Contains reports whether a comma-separated list of options
    27  // contains a particular substr flag. substr must be surrounded by a
    28  // string boundary or commas.
    29  func (o tagOptions) Contains(optionName string) bool {
    30  	if len(o) == 0 {
    31  		return false
    32  	}
    33  	s := string(o)
    34  	for s != "" {
    35  		var next string
    36  		i := strings.Index(s, ",")
    37  		if i >= 0 {
    38  			s, next = s[:i], s[i+1:]
    39  		}
    40  		if s == optionName {
    41  			return true
    42  		}
    43  		s = next
    44  	}
    45  	return false
    46  }
    47  
    48  func isValidTag(s string) bool {
    49  	if s == "" {
    50  		return false
    51  	}
    52  	for _, c := range s {
    53  		switch {
    54  		case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c):
    55  			// Backslash and quote chars are reserved, but
    56  			// otherwise any punctuation chars are allowed
    57  			// in a tag name.
    58  		case !unicode.IsLetter(c) && !unicode.IsDigit(c):
    59  			return false
    60  		}
    61  	}
    62  	return true
    63  }