Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: added func SetRand(r io.Reader) #106

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions id.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,13 @@ package xid

import (
"bytes"
"crypto/sha256"
"crypto/rand"
"crypto/sha256"
"database/sql/driver"
"encoding/binary"
"fmt"
"hash/crc32"
"io"
"io/ioutil"
"os"
"sort"
Expand Down Expand Up @@ -85,6 +86,9 @@ var (

// dec is the decoding map for base32 encoding
dec [256]byte

// rander is seto to default rand.Reader
rander = rand.Reader
)

func init() {
Expand Down Expand Up @@ -119,7 +123,7 @@ func readMachineID() []byte {
copy(id, hw.Sum(nil))
} else {
// Fallback to rand number if machine id can't be gathered
if _, randErr := rand.Reader.Read(id); randErr != nil {
if _, randErr := rander.Read(id); randErr != nil {
panic(fmt.Errorf("xid: cannot get hostname nor generate a random number: %v; %v", err, randErr))
}
}
Expand All @@ -129,7 +133,7 @@ func readMachineID() []byte {
// randInt generates a random uint32
func randInt() uint32 {
b := make([]byte, 3)
if _, err := rand.Reader.Read(b); err != nil {
if _, err := rander.Read(b); err != nil {
panic(fmt.Errorf("xid: cannot generate random number: %v;", err))
}
return uint32(b[0])<<16 | uint32(b[1])<<8 | uint32(b[2])
Expand Down Expand Up @@ -388,3 +392,13 @@ func (s sorter) Swap(i, j int) {
func Sort(ids []ID) {
sort.Sort(sorter(ids))
}

// SetRand sets the random number generator to to an io.Reader.
// Calling with nil sets the random number generator to the default generator.
func SetRand(r io.Reader) {
if r == nil {
rander = rand.Reader
return
}
rander = r
}