Fix randomize vals wrapping around to ngative vals

* Use modulus to ensure values are within valid ranges
This commit is contained in:
Patrick O'brien 2017-03-04 12:17:26 +10:00
parent 9067237f32
commit 60a40eaf48
2 changed files with 28 additions and 14 deletions
randomize

View file

@ -4,6 +4,7 @@ package randomize
import (
"database/sql"
"fmt"
"math"
"math/rand"
"reflect"
"regexp"
@ -71,7 +72,7 @@ func NewSeed() *Seed {
}
func (s *Seed) nextInt() int {
return int(atomic.AddInt64((*int64)(s), 1))
return int(atomic.AddInt64((*int64)(s), 1)) % math.MaxInt32
}
// Struct gets its fields filled with random data based on the seed.
@ -501,23 +502,23 @@ func getStructRandValue(s *Seed, typ reflect.Type) interface{} {
case typeNullFloat64:
return null.NewFloat64(float64(s.nextInt()%10)/10.0+float64(s.nextInt()%10), true)
case typeNullInt:
return null.NewInt(int(int32(s.nextInt())), true)
return null.NewInt(int(int32(s.nextInt()))%math.MaxInt32, true)
case typeNullInt8:
return null.NewInt8(int8(s.nextInt()), true)
return null.NewInt8(int8(s.nextInt())%math.MaxInt8, true)
case typeNullInt16:
return null.NewInt16(int16(s.nextInt()), true)
return null.NewInt16(int16(s.nextInt())%math.MaxInt16, true)
case typeNullInt32:
return null.NewInt32(int32(s.nextInt()), true)
return null.NewInt32(int32(s.nextInt())%math.MaxInt32, true)
case typeNullInt64:
return null.NewInt64(int64(s.nextInt()), true)
case typeNullUint:
return null.NewUint(uint(s.nextInt()), true)
case typeNullUint8:
return null.NewUint8(uint8(s.nextInt()), true)
return null.NewUint8(uint8(s.nextInt())%math.MaxUint8, true)
case typeNullUint16:
return null.NewUint16(uint16(s.nextInt()), true)
return null.NewUint16(uint16(s.nextInt())%math.MaxUint16, true)
case typeNullUint32:
return null.NewUint32(uint32(s.nextInt()), true)
return null.NewUint32(uint32(s.nextInt())%math.MaxUint32, true)
case typeNullUint64:
return null.NewUint64(uint64(s.nextInt()), true)
case typeNullBytes:
@ -590,21 +591,21 @@ func getVariableRandValue(s *Seed, kind reflect.Kind, typ reflect.Type) interfac
case reflect.Int:
return s.nextInt()
case reflect.Int8:
return int8(s.nextInt())
return int8(s.nextInt() % math.MaxInt8)
case reflect.Int16:
return int16(s.nextInt())
return int16(s.nextInt() % math.MaxInt16)
case reflect.Int32:
return int32(s.nextInt())
return int32(s.nextInt() % math.MaxInt32)
case reflect.Int64:
return int64(s.nextInt())
case reflect.Uint:
return uint(s.nextInt())
case reflect.Uint8:
return uint8(s.nextInt())
return uint8(s.nextInt() % math.MaxUint8)
case reflect.Uint16:
return uint16(s.nextInt())
return uint16(s.nextInt() % math.MaxUint16)
case reflect.Uint32:
return uint32(s.nextInt())
return uint32(s.nextInt() % math.MaxUint32)
case reflect.Uint64:
return uint64(s.nextInt())
case reflect.Bool: