implemented UUID.Variant() method

This commit is contained in:
Maxim Bublis 2013-06-18 14:51:58 +04:00
parent 6f0b1e4b83
commit 7e5faa5783
2 changed files with 52 additions and 4 deletions

21
uuid.go
View File

@ -5,6 +5,14 @@ import (
"crypto/rand" "crypto/rand"
) )
// UUID layout variants.
const (
VariantNCS = iota
VariantRFC4122
VariantMicrosoft
VariantFuture
)
type UUID [16]byte type UUID [16]byte
// Returns algorithm version used to generate UUID // Returns algorithm version used to generate UUID
@ -13,6 +21,19 @@ func (u *UUID) Version() uint {
return uint(u[6] >> 4) return uint(u[6] >> 4)
} }
// Returns UUID layout variant.
func (u *UUID) Variant() uint {
switch {
case (u[8] & 0x80) == 0x00:
return VariantNCS
case (u[8] & 0xc0) | 0x80 == 0x80:
return VariantRFC4122
case (u[8] & 0xe0) | 0xc0 == 0xc0:
return VariantMicrosoft
}
return VariantFuture
}
// Returns canonical string representation of UUID: // Returns canonical string representation of UUID:
// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
func (u *UUID) String() string { func (u *UUID) String() string {

View File

@ -22,14 +22,38 @@ func TestSetVersion(t *testing.T) {
} }
func TestVariant(t *testing.T) { func TestVariant(t *testing.T) {
//u := new(UUID) u1 := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
// TODO: implement u.Variant()
if u1.Variant() != VariantNCS {
t.Errorf("Incorrect variant for UUID variant %d: %d", VariantNCS, u1.Variant())
}
u2 := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
if u2.Variant() != VariantRFC4122 {
t.Errorf("Incorrect variant for UUID variant %d: %d", VariantRFC4122, u2.Variant())
}
u3 := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
if u3.Variant() != VariantMicrosoft {
t.Errorf("Incorrect variant for UUID variant %d: %d", VariantMicrosoft, u3.Variant())
}
u4 := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
if u4.Variant() != VariantFuture {
t.Errorf("Incorrect variant for UUID variant %d: %d", VariantFuture, u4.Variant())
}
} }
func TestSetVariant(t *testing.T) { func TestSetVariant(t *testing.T) {
u := new(UUID) u := new(UUID)
u.setVariant() u.setVariant()
// TODO: implement u.Variant()
if u.Variant() != VariantRFC4122 {
t.Errorf("Incorrect variant for UUID after u.setVariant(): %d", u.Variant())
}
} }
func TestString(t *testing.T) { func TestString(t *testing.T) {
@ -51,5 +75,8 @@ func TestNewV4(t *testing.T) {
if u.Version() != 4 { if u.Version() != 4 {
t.Errorf("UUIDv4 generated with incorrect version: %d", u.Version()) t.Errorf("UUIDv4 generated with incorrect version: %d", u.Version())
} }
// TODO: check variant
if u.Variant() != VariantRFC4122 {
t.Errorf("UUIDv4 generated with incorrect variant: %d", u.Variant())
}
} }