forked from hashicorp/packer
-
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.
Simplifies the implementation of common/uuid
- Loading branch information
Showing
1 changed file
with
11 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,32 +1,24 @@ | ||
package uuid | ||
|
||
import ( | ||
"fmt" | ||
"crypto/rand" | ||
"encoding/binary" | ||
"fmt" | ||
"time" | ||
) | ||
|
||
func uint32rand() (value uint32) { | ||
err := binary.Read(rand.Reader, binary.LittleEndian, &value) | ||
if err != nil { | ||
panic(err) | ||
} | ||
return | ||
} | ||
|
||
// Generates a time ordered UUID. Top 32 bits are a timestamp, | ||
// bottom 96 are random. | ||
func TimeOrderedUUID() string { | ||
unix := uint32(time.Now().UTC().Unix()) | ||
rand1 := uint32rand() | ||
rand2 := uint32rand() | ||
rand3 := uint32rand() | ||
|
||
b := make([]byte, 12) | ||
n, err := rand.Read(b) | ||
if n != len(b) { | ||
err = fmt.Errorf("Not enough entropy available") | ||
} | ||
if err != nil { | ||
panic(err) | ||
} | ||
return fmt.Sprintf("%08x-%04x-%04x-%04x-%04x%08x", | ||
unix, | ||
uint16(rand1>>16), | ||
uint16(rand1&0xffff), | ||
uint16(rand2>>16), | ||
uint16(rand2&0xffff), | ||
rand3) | ||
unix, b[0:2], b[2:4], b[4:6], b[6:8], b[8:]) | ||
} |