-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Make ID() generate a time/host based ID. Fixes #2
- Loading branch information
1 parent
771ed2e
commit 6e796a4
Showing
3 changed files
with
87 additions
and
19 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,51 @@ | ||
package gorand | ||
|
||
// ID is a wrapper for GetHex(64). | ||
// 64 bytes should be enough to use as unique IDs to avoid collisions between generated values. | ||
func ID() (string, error) { | ||
return GetHex(64) | ||
import ( | ||
"bytes" | ||
"io" | ||
"time" | ||
) | ||
|
||
var localID [9]byte | ||
|
||
// Initializes the value for the local process run identifier | ||
func init() { | ||
buf, err := GetBytes(9) | ||
if err != nil { | ||
localID = [9]byte{'D', 'e', 'f', 'a', 'u', 'l', 't', 'I', 'D'} | ||
} else { | ||
_, err = io.ReadFull(bytes.NewBuffer(buf), localID[:]) | ||
if err != nil { | ||
localID = [9]byte{'D', 'e', 'f', 'a', 'u', 'l', 't', 'I', 'D'} | ||
} | ||
} | ||
} | ||
|
||
// ID generates a [64]byte random value, using time and local identifier into it. | ||
// | ||
// First (most-significative) 15 bytes: time value | ||
// Next 9 bytes: Local process randomly-generated identifier | ||
// Next 40 bytes: Random value | ||
func ID() (id [64]byte, err error) { | ||
var buf []byte | ||
|
||
// Time part | ||
now, err := time.Now().MarshalBinary() | ||
if err != nil { | ||
return | ||
} | ||
buf = append(buf, now[:15]...) | ||
|
||
// Local ID part | ||
buf = append(buf, localID[:]...) | ||
|
||
// Random value | ||
r, err := GetBytes(40) | ||
if err != nil { | ||
return | ||
} | ||
buf = append(buf, r...) | ||
|
||
_, err = io.ReadFull(bytes.NewBuffer(buf), id[:]) | ||
return | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters