repeated.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package goshared
  2. const repTpl = `
  3. {{ $f := .Field }}{{ $r := .Rules }}
  4. {{ if $r.GetIgnoreEmpty }}
  5. if len({{ accessor . }}) > 0 {
  6. {{ end }}
  7. {{ if $r.GetMinItems }}
  8. {{ if eq $r.GetMinItems $r.GetMaxItems }}
  9. if len({{ accessor . }}) != {{ $r.GetMinItems }} {
  10. err := {{ err . "value must contain exactly " $r.GetMinItems " item(s)" }}
  11. if !all { return err }
  12. errors = append(errors, err)
  13. }
  14. {{ else if $r.MaxItems }}
  15. if l := len({{ accessor . }}); l < {{ $r.GetMinItems }} || l > {{ $r.GetMaxItems }} {
  16. err := {{ err . "value must contain between " $r.GetMinItems " and " $r.GetMaxItems " items, inclusive" }}
  17. if !all { return err }
  18. errors = append(errors, err)
  19. }
  20. {{ else }}
  21. if len({{ accessor . }}) < {{ $r.GetMinItems }} {
  22. err := {{ err . "value must contain at least " $r.GetMinItems " item(s)" }}
  23. if !all { return err }
  24. errors = append(errors, err)
  25. }
  26. {{ end }}
  27. {{ else if $r.MaxItems }}
  28. if len({{ accessor . }}) > {{ $r.GetMaxItems }} {
  29. err := {{ err . "value must contain no more than " $r.GetMaxItems " item(s)" }}
  30. if !all { return err }
  31. errors = append(errors, err)
  32. }
  33. {{ end }}
  34. {{ if $r.GetUnique }}
  35. {{ lookup $f "Unique" }} := {{ if isBytes $f.Type.Element -}}
  36. make(map[string]struct{}, len({{ accessor . }}))
  37. {{ else -}}
  38. make(map[{{ (typ $f).Element }}]struct{}, len({{ accessor . }}))
  39. {{ end -}}
  40. {{ end }}
  41. {{ if or $r.GetUnique (ne (.Elem "" "").Typ "none") }}
  42. for idx, item := range {{ accessor . }} {
  43. _, _ = idx, item
  44. {{ if $r.GetUnique }}
  45. if _, exists := {{ lookup $f "Unique" }}[{{ if isBytes $f.Type.Element }}string(item){{ else }}item{{ end }}]; exists {
  46. err := {{ errIdx . "idx" "repeated value must contain unique items" }}
  47. if !all { return err }
  48. errors = append(errors, err)
  49. } else {
  50. {{ lookup $f "Unique" }}[{{ if isBytes $f.Type.Element }}string(item){{ else }}item{{ end }}] = struct{}{}
  51. }
  52. {{ end }}
  53. {{ render (.Elem "item" "idx") }}
  54. }
  55. {{ end }}
  56. {{ if $r.GetIgnoreEmpty }}
  57. }
  58. {{ end }}
  59. `