Documentation
¶
Overview ¶
This package 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.
If you have a []byte you can simply cast it to the Uuid type.
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 twinj@github.com 2016 MIT licence
Example ¶
package main
import (
"fmt"
"github.com/twinj/uuid"
"github.com/twinj/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)
up, _ := uuid.Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
fmt.Printf("version %d variant %x: %s\n", up.Version(), up.Variant(), up)
uuid.New(up.Bytes())
u1 := uuid.NewV1()
fmt.Printf("version %d variant %x: %s\n", u1.Version(), u1.Variant(), u1)
u4 := uuid.NewV4()
fmt.Printf("version %d variant %x: %s\n", u4.Version(), u4.Variant(), u4)
u3 := uuid.NewV3(u1, u4)
url, _ := url.Parse("www.example.com")
u5 := uuid.NewV5(uuid.NameSpaceURL, url)
if uuid.Equal(u1, u3) {
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(u5, uuid.FormatCanonicalCurly))
uuid.SwitchFormat(uuid.FormatCanonicalBracket)
}
Output:
Index ¶
- Constants
- func Compare(pId, pId2 UUID) int
- func Equal(p1, p2 UUID) bool
- func Formatter(pId UUID, pFormat Format) string
- func Init() error
- func RegisterGenerator(pConfig GeneratorConfig) (err error)
- func RegisterSaver(pSaver Saver)
- func SwitchFormat(pFormat Format)
- func SwitchFormatToUpper(pFormat Format)
- type Domain
- type Format
- type Generator
- type GeneratorConfig
- type HandleError
- type Id
- type Immutable
- type Name
- type Next
- type Node
- type Random
- type Saver
- type Sequence
- type Store
- type Timestamp
- type UUID
- type UniqueName
- type Uuid
- func (o Uuid) Bytes() []byte
- func (o Uuid) MarshalBinary() ([]byte, error)
- func (o Uuid) MarshalText() ([]byte, error)
- func (o *Uuid) Scan(pSrc interface{}) error
- func (o Uuid) Size() int
- func (o Uuid) String() string
- func (o *Uuid) UnmarshalBinary(pBytes []byte) error
- func (o *Uuid) UnmarshalText(pUuid []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 )
Variables ¶
This section is empty.
Functions ¶
func Compare ¶
Compare returns an integer comparing two 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 UUID.
func Formatter ¶
Formatter will return a string representation of the given UUID.
Use this for one time formatting when setting the default 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/twinj/uuid"
)
func main() {
u4 := uuid.NewV4()
fmt.Println(uuid.Formatter(u4, uuid.FormatCanonicalCurly))
}
Output:
func RegisterGenerator ¶
func RegisterGenerator(pConfig GeneratorConfig) (err error)
RegisterGenerator will set the default generator to the given generator 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 ¶
func RegisterSaver(pSaver Saver)
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/twinj/uuid"
"github.com/twinj/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)
u1 := uuid.NewV1()
fmt.Printf("version %d variant %x: %s\n", u1.Version(), u1.Variant(), u1)
}
Output:
func SwitchFormat ¶
func SwitchFormat(pFormat Format)
SwitchFormat switches the default printing format for ALL UUIDs.
The default is the canonical uuid.Format.FormatCanonical which has been optimised for use with this package. It is twice as fast compared to other formats; supplied or given. However, the benchmark for non default formats is still very quick and quite usable. The package has moved away from using fmt.Sprintf which was up to 5 times slower in comparison to custom formats and 10 times slower in comparison to the canonical format.
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 the most likely formats.
Example ¶
package main
import (
"fmt"
"github.com/twinj/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(pFormat Format)
SwitchFormatToUpper is a convenience function to set the Format to uppercase versions of the given constants.
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)" // This is the canonical 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 )
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
// Id as per the type Id func() Node
Id
// HandleError as per the type HandleError func(error) bool
HandleError HandleError
// Next as per the type Next func() Timestamp
Next Next
// Random as per the type Random func([]byte) (int, error)
Random
// Intended to provide a non-volatile store to save the state of the
// generator, the default is nil and to therefore generate a timestamp
// clock sequence with random data. You can register your own save by
// using the uuid.RegisterSaver function or by creating your own
// uuid.Generator instance from which to generate your V1, V2 or V4
// UUIDs.
Saver
// contains filtered or unexported fields
}
Generator is used to create and monitor the running of V1 and V2, and V4 UUIDs. It can be setup to take different implementations for Timestamp, Node and CPRNG retrieval. This is also where the Saver implementation can be given and your error policy for V4 Uuids can be setup.
func NewGenerator ¶
func NewGenerator(pConfig GeneratorConfig) (gen *Generator)
NewGenerator will create a new uuid.Generator with the given functions.
func (*Generator) Error ¶
Error will return any error from the uuid.Generator if a UUID returns as Nil or nil
type GeneratorConfig ¶
GeneratorConfig allows you to setup a new uuid.Generator using uuid.NewGenerator or RegisterGenerator. You can supply your own implementations for CPRNG, Node Id and Timestamp retrieval. You can also adjust the resolution of the default Timestamp spinner and supply your own error handler CPRNG failures.
type HandleError ¶
HandleError provides the user the ability to manage any serious error that may be caused by accessing the standard crypto/rand library. Due to the rarity of this occurrence the error is swallowed by NewV4 functions, which rely on random numbers, the package will then panic. You can change this behaviour by passing in your own HandleError function. With this function you can attempt to fix your CPRNG and then return true to try again. If another error occurs the function will return nil and you can then handle the error by calling uuid.Error or calling Error from your standalone Generator.
type Id ¶
type Id func() Node
Id 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 crypto-random node id. 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 ( Nil Immutable = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" // The following standard UUIDs are for use with V3 or V5 UUIDs. 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" )
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
type Name ¶
type Name string
Name is a string which implements UniqueName and satisfies the Stringer interface. V3 and V5 UUIDs use this for hashing values together to produce UUIDs based on a NameSpace.
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 CPRNG which reads into the given []byte, the package uses crypto/rand.Read by default. You can supply your own CPRNG. The function is used by V4 UUIDs and for setting up V1 and V2 UUIDs via 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() (error, Store)
// Save saves the state to the non volatile store and is called only if
Save(Store)
}
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
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 Timestamp ¶
type Timestamp uint64
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
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 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
}
UUID is the common interface implemented by all UUIDs
type UniqueName ¶
type UniqueName interface {
// Many go types implement this method for use with printing
// Will convert the current type to its native string format
String() string
}
UniqueName is a Stinger interface made for easy passing of any Stringer type into a Hashable UUID.
type Uuid ¶
type Uuid []byte
Uuid is the default UUID implementation. All uuid functions will return this type. All uuid functions should use UUID as their in parameter.
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/twinj/uuid"
)
func main() {
// Must run before using V1 or V2
uuid.Init()
u1 := uuid.NewV1()
fmt.Printf("version %d variant %d: %d\n", u1.Version(), u1.Variant(), u1)
}
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/twinj/uuid"
)
func main() {
// Must run before using V1 or V2
uuid.Init()
u2 := uuid.NewV2(uuid.DomainUser)
fmt.Printf("version %d variant %d: %d\n", u2.Version(), u2.Variant(), u2)
}
Output:
func NewV3 ¶
func NewV3(pNamespace UUID, pNames ...UniqueName) Uuid
NewV3 generates a new RFC4122 version 3 UUID based on the MD5 hash on a namespace UUID and any type which implements the UniqueName interface for the name. For strings and slices cast to a Name type
Example ¶
package main
import (
"fmt"
"github.com/twinj/uuid"
)
func main() {
u, _ := uuid.Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
u3 := uuid.NewV3(u, uuid.Name("test"))
fmt.Printf("version %d variant %x: %s\n", u3.Version(), u3.Variant(), u3)
}
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/twinj/uuid"
)
func main() {
u4 := uuid.NewV4()
fmt.Printf("version %d variant %x: %s\n", u4.Version(), u4.Variant(), u4)
}
Output:
func NewV5 ¶
func NewV5(pNamespace UUID, pNames ...UniqueName) Uuid
NewV5 generates an RFC4122 version 5 UUID based on the SHA-1 hash of a namespace UUID and a unique name.
Example ¶
package main
import (
"fmt"
"github.com/twinj/uuid"
)
func main() {
u5 := uuid.NewV5(uuid.NameSpaceURL, uuid.Name("test"))
fmt.Printf("version %d variant %x: %s\n", u5.Version(), u5.Variant(), u5)
}
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/twinj/uuid"
)
func main() {
u, err := uuid.Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
if err != nil {
fmt.Println("error:", err)
}
fmt.Println(u)
}
Output:
func (Uuid) Bytes ¶
Bytes return the underlying data representation of the Uuid in network byte order
func (Uuid) MarshalBinary ¶
MarshalBinary implements the encoding.BinaryMarshaler interface
func (Uuid) MarshalText ¶
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
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 ¶
UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (*Uuid) UnmarshalText ¶
UnmarshalText implements the encoding.TextUnmarshaler interface. It will support any text that MarshalText can produce.

