Documentation ¶
Overview ¶
Package uuid provides RFC4122 and DCE 1.1 UUIDs.
Use NewV1, NewV2, NewV3, NewV4, NewV5, for generating new UUIDs.
Use New([]byte), NewHex(string), and Parse(string) for creating UUIDs from existing data.
The original version was from Krzysztof Kowalik <chris@nu7hat.ch> Unfortunately, that version was non compliant with RFC4122.
The package has since been redesigned.
The example code in the specification was also used as reference for design.
Copyright (C) 2016 myesui@github.com 2016 MIT licence
Example ¶
package main import ( "fmt" "github.com/myesui/uuid" "github.com/myesui/uuid/savers" "net/url" "time" ) func main() { saver := new(savers.FileSystemSaver) saver.Report = true saver.Duration = time.Second * 3 // Run before any v1 or v2 UUIDs to ensure the savers takes uuid.RegisterSaver(saver) id, _ := uuid.Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8") fmt.Printf("version %d variant %x: %s\n", id.Version(), id.Variant(), id) uuid.New(id.Bytes()) id1 := uuid.NewV1() fmt.Printf("version %d variant %x: %s\n", id1.Version(), id1.Variant(), id1) id4 := uuid.NewV4() fmt.Printf("version %d variant %x: %s\n", id4.Version(), id4.Variant(), id4) id3 := uuid.NewV3(id1, id4) url, _ := url.Parse("www.example.com") id5 := uuid.NewV5(uuid.NameSpaceURL, url) if uuid.Equal(id1, id3) { fmt.Println("Will never happen") } if uuid.Compare(uuid.NameSpaceDNS, uuid.NameSpaceDNS) == 0 { fmt.Println("They are equal") } // Default Format is Canonical fmt.Println(uuid.Formatter(id5, uuid.FormatCanonicalCurly)) uuid.SwitchFormat(uuid.FormatCanonicalBracket) }
Output:
Index ¶
- Constants
- func Compare(pId, pId2 Implementation) int
- func Equal(p1, p2 Implementation) bool
- func Formatter(id Implementation, form Format) string
- func IsNil(uuid Implementation) bool
- func ReadV1(ids []UUID)
- func ReadV4(ids []UUID)
- func RegisterGenerator(config *GeneratorConfig) (err error)
- func RegisterSaver(saver Saver) (err error)
- func SwitchFormat(form Format)
- func SwitchFormatToUpper(form Format)
- type Format
- type Generator
- func (o *Generator) BulkV1(amount int) []UUID
- func (o *Generator) BulkV4(amount int) []UUID
- func (o *Generator) NewHash(hash hash.Hash, names ...interface{}) UUID
- func (o *Generator) NewV1() UUID
- func (o *Generator) NewV2(idType SystemId) UUID
- func (o *Generator) NewV3(namespace Implementation, names ...interface{}) UUID
- func (o *Generator) NewV4() (id UUID)
- func (o *Generator) NewV5(namespace Implementation, names ...interface{}) UUID
- func (o *Generator) ReadV1(ids []UUID)
- func (o *Generator) ReadV4(ids []UUID)
- type GeneratorConfig
- type HandleRandomError
- type Identifier
- type Immutable
- type Implementation
- type Next
- type Node
- type Random
- type Saver
- type Sequence
- type Store
- type SystemId
- type Timestamp
- type UUID
- func BulkV1(amount int) []UUID
- func BulkV4(amount int) []UUID
- func New(data []byte) UUID
- func NewHash(hash hash.Hash, names ...interface{}) UUID
- func NewHex(uuid string) UUID
- func NewV1() UUID
- func NewV2(pDomain SystemId) UUID
- func NewV3(namespace Implementation, names ...interface{}) UUID
- func NewV4() UUID
- func NewV5(namespace Implementation, names ...interface{}) UUID
- func Parse(uuid string) (*UUID, error)
- func (o UUID) Bytes() []byte
- func (o UUID) MarshalBinary() ([]byte, error)
- func (o UUID) MarshalText() ([]byte, error)
- func (o *UUID) Scan(src interface{}) error
- func (o UUID) Size() int
- func (o UUID) String() string
- func (o *UUID) UnmarshalBinary(bytes []byte) error
- func (o *UUID) UnmarshalText(uuid []byte) error
- func (o UUID) Value() (value driver.Value, err error)
- func (o UUID) Variant() uint8
- func (o UUID) Version() Version
- type Version
Examples ¶
Constants ¶
const ( VariantNCS uint8 = 0x00 VariantRFC4122 uint8 = 0x80 // or and A0 if masked with 1F VariantMicrosoft uint8 = 0xC0 VariantFuture uint8 = 0xE0 )
The following are the supported Variants.
Variables ¶
This section is empty.
Functions ¶
func Compare ¶
func Compare(pId, pId2 Implementation) int
Compare returns an integer comparing two Implementation UUIDs lexicographically. The result will be 0 if pId==pId2, -1 if pId < pId2, and +1 if pId > pId2. A nil argument is equivalent to the Nil Immutable UUID.
func Equal ¶
func Equal(p1, p2 Implementation) bool
Equal compares whether each Implementation UUID is the same
func Formatter ¶
func Formatter(id Implementation, form Format) string
Formatter will return a string representation of the given UUID.
Use this for one time formatting when setting the Format using uuid.SwitchFormat would be overkill.
A valid format will have 5 groups of [%x|%X] or follow the pattern, *%[xX]*%[xX]*%[xX]*%[xX]*%[xX]*. If the supplied format does not meet this standard the function will panic. Note any extra uses of [%] outside of the [%x|%X] will also cause a panic.
Example ¶
package main import ( "fmt" "github.com/myesui/uuid" ) func main() { id4 := uuid.NewV4() fmt.Println(uuid.Formatter(id4, uuid.FormatCanonicalCurly)) }
Output:
func IsNil ¶ added in v1.0.0
func IsNil(uuid Implementation) bool
IsNil returns true if Implementation UUID is all zeros?
func ReadV1 ¶ added in v1.0.0
func ReadV1(ids []UUID)
ReadV1 will read a slice of UUIDs. Be careful with the set amount.
func ReadV4 ¶ added in v1.0.0
func ReadV4(ids []UUID)
ReadV4 will read into a slice of UUIDs. Be careful with the set amount. Note: V4 UUIDs require sufficient entropy from the generator. If n == len(ids) err will be nil.
func RegisterGenerator ¶
func RegisterGenerator(config *GeneratorConfig) (err error)
RegisterGenerator will set the package generator with the given configuration Like uuid.Init this can only be called once. Any subsequent calls will have no effect. If you call this you do not need to call uuid.Init.
func RegisterSaver ¶
RegisterSaver register's a uuid.Saver implementation to the default package uuid.Generator. If you wish to save the generator state, this function must be run before any calls to V1 or V2 UUIDs. uuid.RegisterSaver cannot be run in conjunction with uuid.Init. You may implement the uuid.Saver interface or use the provided uuid.Saver's from the uuid/savers package.
Example ¶
package main import ( "fmt" "github.com/myesui/uuid" "github.com/myesui/uuid/savers" "time" ) func main() { saver := new(savers.FileSystemSaver) saver.Report = true saver.Duration = 3 * time.Second // Run before any v1 or v2 UUIDs to ensure the savers takes uuid.RegisterSaver(saver) id1 := uuid.NewV1() fmt.Printf("version %d variant %x: %s\n", id1.Version(), id1.Variant(), id1) }
Output:
func SwitchFormat ¶
func SwitchFormat(form Format)
SwitchFormat switches the default printing format for ALL UUIDs.
The default is canonical uuid.Format.FormatCanonical which has been optimised for use with this package. It is twice as fast compared to other formats. However, non package formats are still very quick.
A valid format will have 5 groups of [%x|%X] or follow the pattern, *%[xX]*%[xX]*%[xX]*%[xX]*%[xX]*. If the supplied format does not meet this standard the function will panic. Note any extra uses of [%] outside of the [%x|%X] will also cause a panic. Constant uuid.Formats have been provided for most likely formats.
Example ¶
package main import ( "fmt" "github.com/myesui/uuid" ) func main() { uuid.SwitchFormat(uuid.FormatCanonicalBracket) u4 := uuid.NewV4() fmt.Printf("version %d variant %x: %s\n", u4.Version(), u4.Variant(), u4) }
Output:
func SwitchFormatToUpper ¶
func SwitchFormatToUpper(form Format)
SwitchFormatToUpper is a convenience function to set the uuid.Format to uppercase versions.
Types ¶
type Format ¶
type Format string
Format represents different styles a UUID can be printed in constants represent a pattern used by the package with which to print a UUID.
const ( FormatHex Format = "%x%x%x%x%x" FormatHexCurly Format = "{%x%x%x%x%x}" FormatHexBracket Format = "(%x%x%x%x%x)" // FormatCanonical is the default format. FormatCanonical Format = "%x-%x-%x-%x-%x" FormatCanonicalCurly Format = "{%x-%x-%x-%x-%x}" FormatCanonicalBracket Format = "(%x-%x-%x-%x-%x)" FormatUrn Format = "urn:uuid:" + FormatCanonical )
The following are the default Formats supplied by the uuid package.
type Generator ¶
type Generator struct { // Access to the store needs to be maintained sync.Mutex // Once ensures that the generator is only setup and initialised once. // This will occur either when you explicitly call the // uuid.Generator.Init function or when a V1 or V2 id is generated. sync.Once // Store contains the current values being used by the Generator. *Store // Identifier as per the type Identifier func() Node Identifier // HandleRandomError as per the type HandleError func(error) bool HandleRandomError // Next as per the type Next func() Timestamp Next // Random as per the type Random func([]byte) (int, error) Random // Saver provides a non-volatile store to save the state of the // generator, the default is nil which will cause the timestamp // clock sequence to populate with random data. You can register your // own saver by using the uuid.RegisterSaver function or by creating // your own uuid.Generator instance. // UUIDs. Saver *log.Logger }
Generator is used to create and monitor the running of V1 and V2, and V4 UUIDs. It can be setup to take custom implementations for Timestamp, Node and Random number retrieval by providing those functions as required. You can also supply a uuid/Saver implementation for saving the state of the generator and you can also provide an error policy for V4 UUIDs and possible errors in the random number generator.
func NewGenerator ¶
func NewGenerator(config *GeneratorConfig) (*Generator, error)
NewGenerator will create a new uuid.Generator with the given functions.
func (*Generator) BulkV1 ¶ added in v1.0.0
BulkV1 will return a slice of V1 UUIDs. Be careful with the set amount.
func (*Generator) BulkV4 ¶ added in v1.0.0
BulkV4 will return a slice of V4 UUIDs. Be careful with the set amount. Note: V4 UUIDs require sufficient entropy from the generator. If n == len(ids) err will be nil.
func (*Generator) NewHash ¶ added in v1.0.0
NewHash generate a UUID based on the given hash implementation. The hash will be of the given names. The version will be set to 0 for Unknown and the variant will be set to VariantFuture.
func (*Generator) NewV1 ¶
NewV1 generates a new RFC4122 version 1 UUID based on a 60 bit timestamp and node id.
func (*Generator) NewV2 ¶
NewV2 generates a new DCE version 2 UUID based on a 60 bit timestamp, node id and the id of the given Id type.
func (*Generator) NewV3 ¶ added in v1.0.0
func (o *Generator) NewV3(namespace Implementation, names ...interface{}) UUID
NewV3 generates a new RFC4122 version 3 UUID based on the MD5 hash of a namespace UUID namespace Implementation UUID and one or more unique names.
func (*Generator) NewV4 ¶ added in v1.0.0
NewV4 generates a cryptographically secure random RFC4122 version 4 UUID. If there is an error with the random number generator this will
func (*Generator) NewV5 ¶ added in v1.0.0
func (o *Generator) NewV5(namespace Implementation, names ...interface{}) UUID
NewV5 generates an RFC4122 version 5 UUID based on the SHA-1 hash of a namespace Implementation UUID and one or more unique names.
type GeneratorConfig ¶
type GeneratorConfig struct { Saver Next Resolution uint Identifier Random HandleRandomError *log.Logger }
GeneratorConfig allows you to setup a new uuid.Generator using uuid.NewGenerator or RegisterGenerator. You can supply your own implementations for the random number generator Random, Identifier and Timestamp retrieval. You can also adjust the resolution of the default Timestamp spinner and supply your own error handler for crypto/rand failures.
type HandleRandomError ¶ added in v1.0.0
HandleRandomError provides the ability to manage a serious error that may be caused by accessing the standard crypto/rand library or the supplied uuid/Random function. Due to the rarity of this occurrence the error is swallowed by the uuid/NewV4 function which relies heavily on random numbers, the package will panic instead if an error occurs.
You can change this behaviour by passing in your own uuid/HandleError function to a custom Generator. This function can attempt to fix the random number generator. If your uuid/HandleError returns true the generator will attempt to generate another V4 uuid. If another error occurs the function will return a fallback v4 uuid generated from the less random math/rand standard library.
Waiting for system entropy may be all that is required in the initial error. If something more serious has occurred, handle appropriately using this function.
type Identifier ¶ added in v1.0.0
type Identifier func() Node
Identifier provides the Node to be used during the life of a uuid.Generator. If it cannot be determined nil should be returned, the package will then provide a node identifier provided by the Random function. The default generator gets a MAC address from the first interface that is 'up' checking net.FlagUp.
type Immutable ¶
type Immutable string
Immutable is an easy to use UUID which can be used as a key or for constants
const ( NameSpaceDNS Immutable = "k\xa7\xb8\x10\x9d\xad\x11р\xb4\x00\xc0O\xd40\xc8" NameSpaceURL Immutable = "k\xa7\xb8\x11\x9d\xad\x11р\xb4\x00\xc0O\xd40\xc8" NameSpaceOID Immutable = "k\xa7\xb8\x12\x9d\xad\x11р\xb4\x00\xc0O\xd40\xc8" NameSpaceX500 Immutable = "k\xa7\xb8\x14\x9d\xad\x11р\xb4\x00\xc0O\xd40\xc8" )
const Nil Immutable = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
Nil represents an empty UUID.
func (Immutable) Bytes ¶
Bytes return the underlying data representation of the Uuid in network byte order
func (Immutable) String ¶
String returns the canonical string representation of the UUID or the uuid.Format the package is set to via uuid.SwitchFormat
func (Immutable) UUID ¶ added in v1.0.0
UUID converts this implementation to the default type uuid.UUID
type Implementation ¶ added in v1.0.0
type Implementation interface { // Bytes retrieves the bytes from the underlying UUID Bytes() []byte // Size is the length of the underlying UUID implementation Size() int // String should return the canonical UUID representation, or the a // given uuid.Format String() string // Variant returns the UUID implementation variant Variant() uint8 // Version returns the version number of the algorithm used to generate // the UUID. Version() Version }
Implementation is the common interface implemented by all UUIDs.
type Next ¶
type Next func() Timestamp
Next provides the next Timestamp value to be used by the next V1 or V2 UUID. The default uses the uuid.spinner which spins at a resolution of 100ns ticks and provides a spin resolution redundancy of 1024 cycles. This ensures that the system is not too quick when generating V1 or V2 UUIDs. Each system requires a tuned Resolution to enhance performance.
type Random ¶
Random provides a random number generator which reads into the given []byte, the package uses crypto/rand.Read by default. You can supply your own implementation or downgrade it to the match/rand package.
The function is used by V4 UUIDs and for setting up V1 and V2 UUIDs in the Generator Init or Register* functions.
type Saver ¶
type Saver interface { // Read is run once, use this to setup your UUID state machine // Read should also return the UUID state from the non volatile store Read() (Store, error) // Save saves the state to the non volatile store and is called only if Save(Store) // Init allows default setup of a new Saver Init() Saver }
Saver is an interface to setup a non volatile store within your system if you wish to use V1 and V2 UUIDs based on your node id and a constant time it is highly recommended to implement this. A default implementation has been provided. FileSystemStorage, the default behaviour of the package is to generate random sequences where a Saver is not specified.
type Sequence ¶
type Sequence uint16
Sequence represents an iterated value to help ensure unique UUID generations values across the same domain, server restarts and clock issues.
type Store ¶
Store is used for storage of UUID generation history to ensure continuous running of the UUID generator between restarts and to monitor synchronicity while generating new V1 or V2 UUIDs.
type SystemId ¶ added in v1.0.0
type SystemId uint8
SystemId denotes the type of id to retrieve from the operating system. That id is then used to create an identifier UUID.
type Timestamp ¶
type Timestamp uint64
Timestamp as per 4.1.4. Timestamp https://www.ietf.org/rfc/rfc4122.txt
The timestamp is a 60-bit value. For UUID version 1, this is
represented by Coordinated Universal Time (UTC) as a count of 100- nanosecond intervals since 00:00:00.00, 15 October 1582 (the date of Gregorian reform to the Christian calendar).
For systems that do not have UTC available, but do have the local time, they may use that instead of UTC, as long as they do so consistently throughout the system. However, this is not recommended since generating the UTC from local time only needs a time zone offset.
For UUID version 3 or 5, the timestamp is a 60-bit value constructed from a name as described in Section 4.3.
For UUID version 4, the timestamp is a randomly or pseudo-randomly generated 60-bit value, as described in Section 4.4.
func Now ¶
func Now() Timestamp
Now converts Unix formatted time to RFC4122 UUID formatted times UUID UTC base time is October 15, 1582. Unix base time is January 1, 1970. Converts time to 100 nanosecond ticks since epoch. Uses time.Now
type UUID ¶
type UUID [length]byte
UUID is the default RFC implementation. All uuid functions will return this type.
func BulkV1 ¶ added in v1.0.0
BulkV1 will return a slice of V1 UUIDs. Be careful with the set amount.
func BulkV4 ¶ added in v1.0.0
BulkV4 will return a slice of V4 UUIDs. Be careful with the set amount. Note: V4 UUIDs require sufficient entropy from the generator. If n == len(ids) err will be nil.
func NewHash ¶ added in v1.0.0
NewHash generate a UUID based on the given hash implementation. The hash will be of the given names. The version will be set to 0 for Unknown and the variant will be set to VariantFuture.
func NewHex ¶
NewHex creates a UUID from a hex string. Will panic if hex string is invalid use Parse otherwise.
func NewV1 ¶
func NewV1() UUID
NewV1 generates a new RFC4122 version 1 UUID based on a 60 bit timestamp and node ID.
Example ¶
package main import ( "fmt" "github.com/myesui/uuid" ) func main() { id1 := uuid.NewV1() fmt.Printf("version %d variant %d: %s\n", id1.Version(), id1.Variant(), id1) }
Output:
func NewV2 ¶
NewV2 generates a new DCE Security version UUID based on a 60 bit timestamp, node id and POSIX UID.
Example ¶
package main import ( "fmt" "github.com/myesui/uuid" ) func main() { id2 := uuid.NewV2(uuid.SystemIdUser) fmt.Printf("version %d variant %d: %s\n", id2.Version(), id2.Variant(), id2) }
Output:
func NewV3 ¶
func NewV3(namespace Implementation, names ...interface{}) UUID
NewV3 generates a new RFC4122 version 3 UUID based on the MD5 hash of a namespace UUID namespace Implementation UUID and one or more unique names.
Example ¶
package main import ( "fmt" "github.com/myesui/uuid" ) func main() { id, _ := uuid.Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8") id3 := uuid.NewV3(id, "test") fmt.Printf("version %d variant %x: %s\n", id3.Version(), id3.Variant(), id3) }
Output:
func NewV4 ¶
func NewV4() UUID
NewV4 generates a new RFC4122 version 4 UUID a cryptographically secure random UUID.
Example ¶
package main import ( "fmt" "github.com/myesui/uuid" ) func main() { id := uuid.NewV4() fmt.Printf("version %d variant %x: %s\n", id.Version(), id.Variant(), id) }
Output:
func NewV5 ¶
func NewV5(namespace Implementation, names ...interface{}) UUID
NewV5 generates an RFC4122 version 5 UUID based on the SHA-1 hash of a namespace Implementation UUID and one or more unique names.
Example ¶
package main import ( "fmt" "github.com/myesui/uuid" ) func main() { id5 := uuid.NewV5(uuid.NameSpaceURL, "test") fmt.Printf("version %d variant %x: %s\n", id5.Version(), id5.Variant(), id5) }
Output:
func Parse ¶
Parse creates a UUID from a valid string representation. Accepts UUID string in following formats:
6ba7b8149dad11d180b400c04fd430c8 6ba7b814-9dad-11d1-80b4-00c04fd430c8 {6ba7b814-9dad-11d1-80b4-00c04fd430c8} urn:uuid:6ba7b814-9dad-11d1-80b4-00c04fd430c8 [6ba7b814-9dad-11d1-80b4-00c04fd430c8] (6ba7b814-9dad-11d1-80b4-00c04fd430c8)
Example ¶
package main import ( "fmt" "github.com/myesui/uuid" ) func main() { id, err := uuid.Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8") if err != nil { fmt.Println("error:", err) } fmt.Println(id) }
Output:
func (UUID) MarshalBinary ¶ added in v1.0.0
MarshalBinary implements the encoding.BinaryMarshaler interface
func (UUID) MarshalText ¶ added in v1.0.0
MarshalText implements the encoding.TextMarshaler interface. It will marshal text into one of the known formats, if you have changed to a custom Format the text be output in canonical format.
func (UUID) String ¶
String returns the canonical string representation of the UUID or the uuid.Format the package is set to via uuid.SwitchFormat
func (*UUID) UnmarshalBinary ¶ added in v1.0.0
UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (*UUID) UnmarshalText ¶ added in v1.0.0
UnmarshalText implements the encoding.TextUnmarshaler interface. It will support any text that MarshalText can produce.
type Version ¶
type Version int
Version represents the type of UUID.