Skip to content

Commit

Permalink
Fill NewV7 from byte 6 instead of 7
Browse files Browse the repository at this point in the history
I was off by 1 in my head. Bytes 0-5 (len 6) are the timestamp
and then bytes 6-15 (len 10) are random data.
  • Loading branch information
cmackenzie1 committed Feb 21, 2023
1 parent 0da4ce5 commit f70e9da
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
8 changes: 4 additions & 4 deletions uuid.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func NewV4() (UUID, error) {
// fill entire uuid with secure, random bytes
_, err := io.ReadFull(rand.Reader, uuid[:])
if err != nil {
return [16]byte{}, err
return UUID{}, err
}

// Set version and variant bits
Expand Down Expand Up @@ -74,13 +74,13 @@ func NewV7() (UUID, error) {
var uuid UUID

t := time.Now()
ms := t.UnixMilli()
ms := t.UnixMilli() & ((1 << 48) - 1) // 48 bit timestamp
binary.BigEndian.PutUint64(uuid[:], uint64(ms<<16)) // lower 48 bits. Right 0 padded

// Fill the rest with random data
_, err := io.ReadFull(rand.Reader, uuid[7:])
_, err := io.ReadFull(rand.Reader, uuid[6:])
if err != nil {
return Nil, err
return UUID{}, err
}

// Set the version and variant bits
Expand Down
8 changes: 8 additions & 0 deletions uuid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,11 @@ func TestUUID_Duplicates(t *testing.T) {
})
}
}

func TestPrint(t *testing.T) {
u, _ := NewV4()
t.Logf("v4: %s %v", u, u[:])

u, _ = NewV7()
t.Logf("v7: %s %v", u, u[:])
}

0 comments on commit f70e9da

Please sign in to comment.