diff --git a/uuid.go b/uuid.go index 23161a8..1320d60 100644 --- a/uuid.go +++ b/uuid.go @@ -97,6 +97,13 @@ func ParseBytes(b []byte) (UUID, error) { return uuid, nil } +// FromBytes creates a new UUID from a byte slice. Returns an error if the slice +// does not have a length of 16. The bytes are copied from the slice. +func FromBytes(b []byte) (uuid UUID, err error) { + err = uuid.UnmarshalBinary(b) + return uuid, err +} + // Must returns uuid if err is nil and panics otherwise. func Must(uuid UUID, err error) UUID { if err != nil { diff --git a/uuid_test.go b/uuid_test.go index 2426168..3ecd8c2 100644 --- a/uuid_test.go +++ b/uuid_test.go @@ -121,6 +121,25 @@ func TestUUID(t *testing.T) { } } +func TestFromBytes(t *testing.T) { + b := []byte{ + 0x7d, 0x44, 0x48, 0x40, + 0x9d, 0xc0, + 0x11, 0xd1, + 0xb2, 0x45, + 0x5f, 0xfd, 0xce, 0x74, 0xfa, 0xd2, + } + uuid, err := FromBytes(b) + if err != nil { + t.Fatalf("%s", err) + } + for i := 0; i < len(uuid); i++ { + if b[i] != uuid[i] { + t.Fatalf("FromBytes() got %v expected %v\b", uuid[:], b) + } + } +} + func TestConstants(t *testing.T) { for x, tt := range constants { v, ok := tt.c.(fmt.Stringer)