diff --git a/go.mod b/go.mod index fc84cd7..7258c3e 100644 --- a/go.mod +++ b/go.mod @@ -1 +1,3 @@ -module github.com/google/uuid +module github.com/inliquid/uuid + +require gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce diff --git a/marshal.go b/marshal.go index 14bd340..882685a 100644 --- a/marshal.go +++ b/marshal.go @@ -4,7 +4,19 @@ package uuid -import "fmt" +import ( + "errors" + "fmt" + + "gopkg.in/mgo.v2/bson" +) + +var ( + // By default, new (recommended) UUID subtype/kind (0x04) is used, see + // https://studio3t.com/knowledge-base/articles/mongodb-best-practices-uuid-data/#binary-subtypes-0x03-and-0x04 and + // http://bsonspec.org/spec.html for details. Can be changed with SetBSONKind. + bsonKind byte = 0x04 +) // MarshalText implements encoding.TextMarshaler. func (uuid UUID) MarshalText() ([]byte, error) { @@ -36,3 +48,41 @@ func (uuid *UUID) UnmarshalBinary(data []byte) error { copy(uuid[:], data) return nil } + +// GetBSON implements bson.Getter for marshaling UUID in BSON binary UUID format. +// By default Kind of 0x04 (new UUID) will be used. Can be changed with SetBSONKind. +func (uuid UUID) GetBSON() (interface{}, error) { + toMarshal := bson.Binary{ + Kind: bsonKind, + Data: uuid[:], + } + + return toMarshal, nil +} + +// SetBSON implements bson.Setter for unmarshaling UUID from BSON binary UUID format. +// By default Kind of 0x04 (new UUID) will be used. Can be changed with SetBSONKind. +func (uuid *UUID) SetBSON(raw bson.Raw) error { + var toUnmarshal bson.Binary + + err := raw.Unmarshal(&toUnmarshal) + if err != nil { + return err + } + + *uuid, err = FromBytes(toUnmarshal.Data) + + return err +} + +// SetBSONKind changes BSON UUID Kind which will be used by GetBSON and SetBSON. Only values of +// 0x03 (Legacy UUID) or 0x04 (new UUID) can be used, SetBSONKind returns error when requested kind is different. +func SetBSONKind(kind byte) error { + if kind < 0x03 || kind > 0x04 { + return errors.New("requested BSON UUID kind is not allowed") + } + + bsonKind = kind + + return nil +}