open-consul/vendor/github.com/hashicorp/go-uuid/uuid.go

84 lines
1.9 KiB
Go
Raw Normal View History

package uuid
import (
"crypto/rand"
"encoding/hex"
"fmt"
2020-05-12 01:59:29 +00:00
"io"
)
2016-08-10 00:00:16 +00:00
// GenerateRandomBytes is used to generate random bytes of given size.
func GenerateRandomBytes(size int) ([]byte, error) {
2020-05-12 01:59:29 +00:00
return GenerateRandomBytesWithReader(size, rand.Reader)
}
// GenerateRandomBytesWithReader is used to generate random bytes of given size read from a given reader.
func GenerateRandomBytesWithReader(size int, reader io.Reader) ([]byte, error) {
if reader == nil {
return nil, fmt.Errorf("provided reader is nil")
}
2016-08-10 00:00:16 +00:00
buf := make([]byte, size)
2020-05-12 01:59:29 +00:00
if _, err := io.ReadFull(reader, buf); err != nil {
2016-08-10 00:00:16 +00:00
return nil, fmt.Errorf("failed to read random bytes: %v", err)
}
2016-08-10 00:00:16 +00:00
return buf, nil
}
2020-05-12 01:59:29 +00:00
2019-03-26 21:50:42 +00:00
const uuidLen = 16
2016-08-10 00:00:16 +00:00
// GenerateUUID is used to generate a random UUID
func GenerateUUID() (string, error) {
2020-05-12 01:59:29 +00:00
return GenerateUUIDWithReader(rand.Reader)
}
// GenerateUUIDWithReader is used to generate a random UUID with a given Reader
func GenerateUUIDWithReader(reader io.Reader) (string, error) {
if reader == nil {
return "", fmt.Errorf("provided reader is nil")
}
buf, err := GenerateRandomBytesWithReader(uuidLen, reader)
2016-08-10 00:00:16 +00:00
if err != nil {
return "", err
}
return FormatUUID(buf)
}
func FormatUUID(buf []byte) (string, error) {
2019-03-26 21:50:42 +00:00
if buflen := len(buf); buflen != uuidLen {
return "", fmt.Errorf("wrong length byte slice (%d)", buflen)
}
2019-03-26 21:50:42 +00:00
return fmt.Sprintf("%x-%x-%x-%x-%x",
buf[0:4],
buf[4:6],
buf[6:8],
buf[8:10],
buf[10:16]), nil
}
func ParseUUID(uuid string) ([]byte, error) {
2019-03-26 21:50:42 +00:00
if len(uuid) != 2 * uuidLen + 4 {
return nil, fmt.Errorf("uuid string is wrong length")
}
2019-03-26 21:50:42 +00:00
if uuid[8] != '-' ||
uuid[13] != '-' ||
uuid[18] != '-' ||
uuid[23] != '-' {
return nil, fmt.Errorf("uuid is improperly formatted")
}
hexStr := uuid[0:8] + uuid[9:13] + uuid[14:18] + uuid[19:23] + uuid[24:36]
ret, err := hex.DecodeString(hexStr)
if err != nil {
return nil, err
}
2019-03-26 21:50:42 +00:00
if len(ret) != uuidLen {
return nil, fmt.Errorf("decoded hex is the wrong length")
}
return ret, nil
}