Browse Source

Refactor uuid.go (#9)

Introduce a const uuidLen = 16 to replace some of the magic numbers.

Prefer a rune literal '-' over a temp byte slice []byte("-").

Let Printf format byte slices with %x, assuming the input slices have correct lengths (if they don't, that's a grave bug)
NODA, Kai 7 years ago
parent
commit
4f571afc59
1 changed files with 12 additions and 12 deletions
  1. 12 12
      uuid.go

+ 12 - 12
uuid.go

@@ -15,9 +15,11 @@ func GenerateRandomBytes(size int) ([]byte, error) {
 	return buf, nil
 }
 
+const uuidLen = 16
+
 // GenerateUUID is used to generate a random UUID
 func GenerateUUID() (string, error) {
-	buf, err := GenerateRandomBytes(16)
+	buf, err := GenerateRandomBytes(uuidLen)
 	if err != nil {
 		return "", err
 	}
@@ -25,11 +27,11 @@ func GenerateUUID() (string, error) {
 }
 
 func FormatUUID(buf []byte) (string, error) {
-	if len(buf) != 16 {
-		return "", fmt.Errorf("wrong length byte slice (%d)", len(buf))
+	if buflen := len(buf); buflen != uuidLen {
+		return "", fmt.Errorf("wrong length byte slice (%d)", buflen)
 	}
 
-	return fmt.Sprintf("%08x-%04x-%04x-%04x-%12x",
+	return fmt.Sprintf("%x-%x-%x-%x-%x",
 		buf[0:4],
 		buf[4:6],
 		buf[6:8],
@@ -38,16 +40,14 @@ func FormatUUID(buf []byte) (string, error) {
 }
 
 func ParseUUID(uuid string) ([]byte, error) {
-	if len(uuid) != 36 {
+	if len(uuid) != 2 * uuidLen + 4 {
 		return nil, fmt.Errorf("uuid string is wrong length")
 	}
 
-	hyph := []byte("-")
-
-	if uuid[8] != hyph[0] ||
-		uuid[13] != hyph[0] ||
-		uuid[18] != hyph[0] ||
-		uuid[23] != hyph[0] {
+	if uuid[8] != '-' ||
+		uuid[13] != '-' ||
+		uuid[18] != '-' ||
+		uuid[23] != '-' {
 		return nil, fmt.Errorf("uuid is improperly formatted")
 	}
 
@@ -57,7 +57,7 @@ func ParseUUID(uuid string) ([]byte, error) {
 	if err != nil {
 		return nil, err
 	}
-	if len(ret) != 16 {
+	if len(ret) != uuidLen {
 		return nil, fmt.Errorf("decoded hex is the wrong length")
 	}