|
| 1 | +package mutator |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/binary" |
| 5 | + "math/rand" |
| 6 | + "unsafe" |
| 7 | +) |
| 8 | + |
| 9 | +var nativeEndian binary.ByteOrder |
| 10 | + |
| 11 | +func init() { |
| 12 | + buf := [2]byte{} |
| 13 | + *(*uint16)(unsafe.Pointer(&buf[0])) = uint16(0xABCD) |
| 14 | + |
| 15 | + switch buf { |
| 16 | + case [2]byte{0xCD, 0xAB}: |
| 17 | + nativeEndian = binary.LittleEndian |
| 18 | + case [2]byte{0xAB, 0xCD}: |
| 19 | + nativeEndian = binary.BigEndian |
| 20 | + default: |
| 21 | + panic("Could not determine native endian.") |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +// Return random integer from [0, count) |
| 26 | +func getRandomRange(src *rand.Rand, count int) int { |
| 27 | + // validate count |
| 28 | + // because rand panics if count <= 0 |
| 29 | + if count <= 0 { |
| 30 | + return 0 |
| 31 | + } |
| 32 | + return src.Intn(count) |
| 33 | +} |
| 34 | + |
| 35 | +func MutateInt64(src *rand.Rand, value *int64) error { |
| 36 | + return mutateValue(src, value) |
| 37 | +} |
| 38 | + |
| 39 | +func MutateInt32(src *rand.Rand, value *int32) error { |
| 40 | + return mutateValue(src, value) |
| 41 | +} |
| 42 | + |
| 43 | +func MutateUint64(src *rand.Rand, value *uint64) error { |
| 44 | + return mutateValue(src, value) |
| 45 | +} |
| 46 | + |
| 47 | +func MutateUint32(src *rand.Rand, value *uint32) error { |
| 48 | + return mutateValue(src, value) |
| 49 | +} |
| 50 | + |
| 51 | +func MutateFloat32(src *rand.Rand, value *float32) error { |
| 52 | + return mutateValue(src, value) |
| 53 | +} |
| 54 | + |
| 55 | +func MutateFloat64(src *rand.Rand, value *float64) error { |
| 56 | + return mutateValue(src, value) |
| 57 | +} |
| 58 | + |
| 59 | +func MutateBool(src *rand.Rand, value *bool) error { |
| 60 | + return mutateValue(src, value) |
| 61 | +} |
| 62 | + |
| 63 | +// Return random bool value |
| 64 | +func GetRandomBool(src *rand.Rand) bool { |
| 65 | + return GetRandomBoolN(src, 2) |
| 66 | +} |
| 67 | + |
| 68 | +// Return true with probability about 1-of-n. |
| 69 | +func GetRandomBoolN(src *rand.Rand, n int) bool { |
| 70 | + val := getRandomRange(src, n) |
| 71 | + return val == 0 |
| 72 | +} |
| 73 | + |
| 74 | +// Flips random bit in the buffer. |
| 75 | +func flipBit(src *rand.Rand, size int, data []byte) { |
| 76 | + if len(data) == 0 { |
| 77 | + return |
| 78 | + } |
| 79 | + bit := getRandomRange(src, size*8) |
| 80 | + |
| 81 | + data[bit/8] ^= (1 << (bit % 8)) |
| 82 | +} |
0 commit comments