aboutsummaryrefslogtreecommitdiff
path: root/uuid_source.go
diff options
context:
space:
mode:
Diffstat (limited to 'uuid_source.go')
-rw-r--r--uuid_source.go30
1 files changed, 22 insertions, 8 deletions
diff --git a/uuid_source.go b/uuid_source.go
index 211b052..83a569c 100644
--- a/uuid_source.go
+++ b/uuid_source.go
@@ -5,10 +5,18 @@ import (
"crypto/rand"
)
+// A UuidSource holds a random number generator and generates UUIDs using it as its source.
+//
+// It is useful when a process need its own random number generator,
+// e.g. when running some processes concurrently.
type UuidSource struct {
rander io.Reader
}
+// Creates a new UuidSource which holds its own random number generator.
+//
+// Calling NewSource with nil sets the random number generator to a default
+// generator.
func NewSource(r io.Reader) UuidSource {
var uuidSource UuidSource
uuidSource.SetRand(r)
@@ -16,6 +24,12 @@ func NewSource(r io.Reader) UuidSource {
}
+// SetRand sets the random number generator of the UuidSource to r, which implements io.Reader.
+// If r.Read returns an error when the package requests random data then
+// a panic will be issued.
+//
+// Calling SetRand with nil sets the random number generator to a default
+// generator.
func (uuidSource *UuidSource) SetRand(r io.Reader) {
if r == nil {
uuidSource.rander = rand.Reader
@@ -24,17 +38,17 @@ func (uuidSource *UuidSource) SetRand(r io.Reader) {
uuidSource.rander = r
}
+// NewRandom returns a Random (Version 4) UUID based on the random number generator in the UuidSource.
+//
+// See more detailed explanation here: https://godoc.org/github.com/google/uuid#NewRandom
func (uuidSource UuidSource) NewRandom() (UUID, error) {
- var uuid UUID
- _, err := io.ReadFull(uuidSource.rander, uuid[:])
- if err != nil {
- return Nil, err
- }
- uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4
- uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10
- return uuid, nil
+ return newRandom(uuidSource.rander)
}
+// New creates a new random UUID based on the random number generator in the UuidSource or panics. New is equivalent to
+// the expression
+//
+// uuid.Must(uuid.NewRandom())
func (uuidSource UuidSource) New() UUID {
return Must(uuidSource.NewRandom())
}