NewLength returns an int that validates the generator attribute length validations if any.
(a *AttributeExpr, r *ExampleGenerator)
| 93 | // NewLength returns an int that validates the generator attribute length |
| 94 | // validations if any. |
| 95 | func NewLength(a *AttributeExpr, r *ExampleGenerator) int { |
| 96 | if hasLengthValidation(a) { |
| 97 | minlength, maxlength := math.Inf(1), math.Inf(-1) |
| 98 | if a.Validation.MinLength != nil { |
| 99 | minlength = float64(*a.Validation.MinLength) |
| 100 | } |
| 101 | if a.Validation.MaxLength != nil { |
| 102 | maxlength = float64(*a.Validation.MaxLength) |
| 103 | } |
| 104 | count := 0 |
| 105 | switch { |
| 106 | case math.IsInf(minlength, 1): |
| 107 | count = int(maxlength) - (r.Int() % 3) |
| 108 | case math.IsInf(maxlength, -1): |
| 109 | count = int(minlength) + (r.Int() % 3) |
| 110 | case minlength < maxlength: |
| 111 | diff := min(int(maxlength-minlength), maxLength) |
| 112 | count = int(minlength) + (r.Int() % diff) |
| 113 | case minlength == maxlength: |
| 114 | count = int(minlength) |
| 115 | default: |
| 116 | panic("Validation: MinLength > MaxLength") |
| 117 | } |
| 118 | if count > maxLength { |
| 119 | count = maxLength |
| 120 | } |
| 121 | return count |
| 122 | } |
| 123 | return r.ArrayLength() |
| 124 | } |
| 125 | |
| 126 | func hasLengthValidation(a *AttributeExpr) bool { |
| 127 | if a.Validation == nil { |
no test coverage detected