Skip to content

Commit

Permalink
add FromBytes constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
loderunner committed Nov 10, 2017
1 parent e367a34 commit 5c50970
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
7 changes: 7 additions & 0 deletions uuid.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
19 changes: 19 additions & 0 deletions uuid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 5c50970

Please sign in to comment.