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

Add ReadRandom and reimplement NewRandomFromReader using it #89

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 14 additions & 0 deletions uuid_test.go
Expand Up @@ -5,6 +5,7 @@
package uuid

import (
"bufio"
"bytes"
"fmt"
"os"
Expand Down Expand Up @@ -700,3 +701,16 @@ func BenchmarkUUID_NewPooled(b *testing.B) {
}
})
}

func BenchmarkUUID_BufioReadRandom(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
r := bufio.NewReaderSize(rander, randPoolSize)
var uuid UUID
for pb.Next() {
err := ReadRandom(r, &uuid)
if err != nil {
b.Fatal(err)
}
}
})
}
16 changes: 13 additions & 3 deletions version4.go
Expand Up @@ -38,21 +38,31 @@ func NewString() string {
// year and having one duplicate.
func NewRandom() (UUID, error) {
if !poolEnabled {
return NewRandomFromReader(rander)
var uuid UUID
return uuid, ReadRandom(rander, &uuid)
}
return newRandomFromPool()
}

// NewRandomFromReader returns a UUID based on bytes read from a given io.Reader.
func NewRandomFromReader(r io.Reader) (UUID, error) {
var uuid UUID
return uuid, ReadRandom(r, &uuid)
}

// ReadRandom fills a random (version 4) UUID based on bytes read from a
// given io.Reader. When combined with e.g. a bufio.Reader, this is an
// efficient way to generate many UUIDs quickly.
//
// If an error was returned, the UUID may still be modified.
func ReadRandom(r io.Reader, uuid *UUID) error {
_, err := io.ReadFull(r, uuid[:])
if err != nil {
return Nil, err
return err
}
uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4
uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10
return uuid, nil
return nil
}

func newRandomFromPool() (UUID, error) {
Expand Down