map.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package goshared
  2. const mapTpl = `
  3. {{ $f := .Field }}{{ $r := .Rules }}
  4. {{ if $r.GetIgnoreEmpty }}
  5. if len({{ accessor . }}) > 0 {
  6. {{ end }}
  7. {{ if $r.GetMinPairs }}
  8. {{ if eq $r.GetMinPairs $r.GetMaxPairs }}
  9. if len({{ accessor . }}) != {{ $r.GetMinPairs }} {
  10. err := {{ err . "value must contain exactly " $r.GetMinPairs " pair(s)" }}
  11. if !all { return err }
  12. errors = append(errors, err)
  13. }
  14. {{ else if $r.MaxPairs }}
  15. if l := len({{ accessor . }}); l < {{ $r.GetMinPairs }} || l > {{ $r.GetMaxPairs }} {
  16. err := {{ err . "value must contain between " $r.GetMinPairs " and " $r.GetMaxPairs " pairs, inclusive" }}
  17. if !all { return err }
  18. errors = append(errors, err)
  19. }
  20. {{ else }}
  21. if len({{ accessor . }}) < {{ $r.GetMinPairs }} {
  22. err := {{ err . "value must contain at least " $r.GetMinPairs " pair(s)" }}
  23. if !all { return err }
  24. errors = append(errors, err)
  25. }
  26. {{ end }}
  27. {{ else if $r.MaxPairs }}
  28. if len({{ accessor . }}) > {{ $r.GetMaxPairs }} {
  29. err := {{ err . "value must contain no more than " $r.GetMaxPairs " pair(s)" }}
  30. if !all { return err }
  31. errors = append(errors, err)
  32. }
  33. {{ end }}
  34. {{ if or $r.GetNoSparse (ne (.Elem "" "").Typ "none") (ne (.Key "" "").Typ "none") }}
  35. for key, val := range {{ accessor . }} {
  36. _ = val
  37. {{ if $r.GetNoSparse }}
  38. if val == nil {
  39. err := {{ errIdx . "key" "value cannot be sparse, all pairs must be non-nil" }}
  40. if !all { return err }
  41. errors = append(errors, err)
  42. }
  43. {{ end }}
  44. {{ render (.Key "key" "key") }}
  45. {{ render (.Elem "val" "key") }}
  46. }
  47. {{ end }}
  48. {{ if $r.GetIgnoreEmpty }}
  49. }
  50. {{ end }}
  51. `