Skip to content

Commit

Permalink
Create RandomInt Function
Browse files Browse the repository at this point in the history
- Memory efficient solution for RandomInt func
- Improve error handling by logging them vice returning the type
- Use RandomInt() instead

Resolves: sashabaranov#487
  • Loading branch information
ealvar3z committed Sep 14, 2023
1 parent bd1bb20 commit d8c78aa
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
2 changes: 1 addition & 1 deletion engines_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func TestListEngines(t *testing.T) {
client, server, teardown := setupOpenAITestServer()
defer teardown()
server.RegisterHandler("/v1/engines", func(w http.ResponseWriter, r *http.Request) {
engines := make([]Engine, 5)
engines := make([]Engine, test.RandomInt(5))
for i := range engines {
engines[i] = RandomEngine()
}
Expand Down
21 changes: 19 additions & 2 deletions internal/test/random.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ package test

import (
"crypto/rand"
"log"
"strings"
)

const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const strLen = 10
const bitLen = 0xFF

// See StackOverflow answer:
// https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-go
Expand All @@ -20,7 +22,7 @@ func RandomString() string {
randomByte := make([]byte, 1)
_, err := rand.Read(randomByte)
if err != nil {
return ""
log.Fatalf("Error generating random string: %v", err)
}
randomIndex := randomByte[0] % byte(len(letters))
sb.WriteByte(letters[randomIndex])
Expand All @@ -29,6 +31,21 @@ func RandomString() string {
return sb.String()
}

// RandomInt generates a random integer between 0 (inclusive) and 'max'
// (exclusive). We uses the crypto/rand library for generating random
// bytes. It then performs a bitwise AND operation with 0xFF to keep only the
// least significant 8 bits, effectively converting the byte to an integer. The
// resulting integer is then modulo'd with 'max'.
func RandomInt(max int) int {
var b [1]byte
_, err := rand.Read(b[:])
if err != nil {
log.Fatalf("Error generating random int: %v", err)
}
n := int(b[0]&bitLen) % max
return n
}

// RandomBool generates a cryptographically secure random boolean value.
// It reads a single byte from the crypto/rand library and uses its least
// significant bit to determine the boolean value. The function returns
Expand All @@ -37,7 +54,7 @@ func RandomBool() bool {
var b [1]byte
_, err := rand.Read(b[:])
if err != nil {
return false
log.Fatalf("Error generating random bool: %v", err)
}
return b[0]&1 == 1
}

0 comments on commit d8c78aa

Please sign in to comment.