Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
module github.com/google/uuid
module github.com/inliquid/uuid

require gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce
52 changes: 51 additions & 1 deletion marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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
}