Skip to content

Commit

Permalink
Merge pull request #22 from nano-interactive/feature/randint
Browse files Browse the repository at this point in the history
[Feature] Add randint for generating unsinged integers of every size
  • Loading branch information
dusnm authored Apr 24, 2024
2 parents 181f164 + 48fb84c commit 3b8aad8
Show file tree
Hide file tree
Showing 2 changed files with 123 additions and 0 deletions.
59 changes: 59 additions & 0 deletions randint/randint.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package randint

import (
"crypto/rand"
"encoding/binary"
)

const (
uint8Len = 1
uint16Len = 2
uint32Len = 4
uint64Len = 8
)

func generateBytes(length int) ([]byte, error) {
b := make([]byte, length)

if _, err := rand.Read(b); err != nil {
return nil, err
}

return b, nil
}

func Uint8() (uint8, error) {
b, err := generateBytes(uint8Len)
if err != nil {
return 0, err
}

return uint8(b[0]), nil
}

func Uint16() (uint16, error) {
b, err := generateBytes(uint16Len)
if err != nil {
return 0, err
}

return binary.NativeEndian.Uint16(b), nil
}

func Uint32() (uint32, error) {
b, err := generateBytes(uint32Len)
if err != nil {
return 0, err
}

return binary.NativeEndian.Uint32(b), nil
}

func Uint64() (uint64, error) {
b, err := generateBytes(uint64Len)
if err != nil {
return 0, err
}

return binary.NativeEndian.Uint64(b), nil
}
64 changes: 64 additions & 0 deletions randint/randint_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package randint

import (
"testing"
"unsafe"

"github.com/stretchr/testify/require"
)

func TestUint8(t *testing.T) {
t.Parallel()

// arrange
assert := require.New(t)

// act
v, err := Uint8()

// assert
assert.NoError(err)
assert.Equal(uint8Len, int(unsafe.Sizeof(v)))
}

func TestUint16(t *testing.T) {
t.Parallel()

// arrange
assert := require.New(t)

// act
v, err := Uint16()

// assert
assert.NoError(err)
assert.Equal(uint16Len, int(unsafe.Sizeof(v)))
}

func TestUint32(t *testing.T) {
t.Parallel()

// arrange
assert := require.New(t)

// act
v, err := Uint32()

// assert
assert.NoError(err)
assert.Equal(uint32Len, int(unsafe.Sizeof(v)))
}

func TestUint64(t *testing.T) {
t.Parallel()

// arrange
assert := require.New(t)

// act
v, err := Uint64()

// assert
assert.NoError(err)
assert.Equal(uint64Len, int(unsafe.Sizeof(v)))
}

0 comments on commit 3b8aad8

Please sign in to comment.