Ver código fonte

Merge pull request #1 from hashicorp/add-parse-uuid

Add ParseUUID method to get the bytes out of a generated UUID.
Jeff Mitchell 10 anos atrás
pai
commit
36289988d8
2 arquivos alterados com 51 adições e 0 exclusões
  1. 28 0
      uuid.go
  2. 23 0
      uuid_test.go

+ 28 - 0
uuid.go

@@ -2,6 +2,7 @@ package uuid
 
 import (
 	"crypto/rand"
+	"encoding/hex"
 	"fmt"
 )
 
@@ -27,3 +28,30 @@ func FormatUUID(buf []byte) (string, error) {
 		buf[8:10],
 		buf[10:16]), nil
 }
+
+func ParseUUID(uuid string) ([]byte, error) {
+	if len(uuid) != 36 {
+		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] {
+		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
+	}
+	if len(ret) != 16 {
+		return nil, fmt.Errorf("decoded hex is the wrong length")
+	}
+
+	return ret, nil
+}

+ 23 - 0
uuid_test.go

@@ -1,6 +1,8 @@
 package uuid
 
 import (
+	"crypto/rand"
+	"reflect"
 	"regexp"
 	"testing"
 )
@@ -26,3 +28,24 @@ func TestGenerateUUID(t *testing.T) {
 		}
 	}
 }
+
+func TestParseUUID(t *testing.T) {
+	buf := make([]byte, 16)
+	if _, err := rand.Read(buf); err != nil {
+		t.Fatalf("failed to read random bytes: %v", err)
+	}
+
+	uuidStr, err := FormatUUID(buf)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	parsedStr, err := ParseUUID(uuidStr)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	if !reflect.DeepEqual(parsedStr, buf) {
+		t.Fatalf("mismatched buffers")
+	}
+}