uuid

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 27, 2017 License: MIT Imports: 18 Imported by: 1,410

README

Go UUID implementation

license GoDoc Build Status Build Status Coverage Status Go Report Card

This package provides RFC 4122 and DCE 1.1 compliant UUIDs. It will generate the following:

  • Version 1: based on a Timestamp and MAC address as Node id
  • Version 2: based on DCE Security - Experimental
  • Version 3: based on MD5 hash
  • Version 4: based on cryptographically secure random numbers
  • Version 5: based on SHA-1 hash

Functions NewV1, NewV2, NewV3, NewV4, NewV5, New, NewHex and Parse() for generating version 1, 2, 3, 4 and 5 Uuid's

Requirements

Will generally support last 3 versions of Go.

  • 1.8
  • 1.7
  • 1.6

Installation

Use the go tool:

$ go get gopkg.in/myesui/uuid.v1

See gopkg.in

Typical Usage

See documentation and examples for more information.

All UUIDs

import "gopkg.in/myesui/uuid.v1"

id, _ := uuid.Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")

if uuid.Equal(id, uuid.NameSpaceDNS) {
    fmt.Println("Alas these are equal")
}

if uuid.Compare(id, uuid.NameSpaceDNS) == 0 {
    fmt.Println("They are also equal")
}

if uuid.Compare(id, uuid.NameSpaceX500) == -1 {
    fmt.Println("id < uuid.NameSpaceX500")
}

if uuid.Compare(uuid.NameSpaceX50, id) == 1 {
    fmt.Println("uuid.NameSpaceX500 > id")
}

// Default Format is FormatCanonical
fmt.Println(uuid.Formatter(id, uuid.FormatCanonicalCurly))

uuid.SwitchFormat(uuid.FormatCanonicalBracket)

Formatting UUIDs

The default format is uuid.FormatCanonical xxxxxxxx-xxxx-xxxx-xxxx-xxxxxx

Any call to uuid.String() will produce this output.

The format is twice as fast as the others at producing a string from the bytes.

To change to another format permanently use:

uuid.SwitchFormat(uuid.Format*) 
uuid.SwitchFormatToUpper(uuid.Format*) 

Once this has been called in an init function all UUID.String() calls will use the new format.

Available formats:

FormatHex              = xxxxxxxxxxxxxxxxxxxxxxxxxx
FormatHexCurly         = {xxxxxxxxxxxxxxxxxxxxxxxxxx}
FormatHexBracket       = (xxxxxxxxxxxxxxxxxxxxxxxxxx)

// This is the default format.
FormatCanonical Format = xxxxxxxx-xxxx-xxxx-xxxx-xxxxxx

FormatCanonicalCurly   = {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxx}
FormatCanonicalBracket = (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxx)
FormatUrn              = urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxx

The uuid.Formatter function also exists and is only ever meant to be used for one time prints where a different format from the default or switched format is required. You can supply your own format as long as it fits the pattern.
which contains %x for the five groups in an UUID. Eg: FormatCanonical = %x-%x-%x-%x-%x

You can also stwict to a custom format

Note: AT this time cutsom formats are not supported for TextMarshalling. If a custom format is deteced it will use the canonical format. Use a call to String() and save as a string instead. 

Version 1 and 2 UUIDs

import "gopkg.in/myesui/uuid.v1"

id := uuid.NewV1()
fmt.Println(id)
fmt.Printf("version %s variant %x: %s\n", u1.Version(), u1.Variant(), id)

id = uuid.NewV2(uuid.DomainUser)
fmt.Println(id)
fmt.Printf("version %s variant %x: %s\n", u1.Version(), u1.Variant(), id)

ids := uuid.BulkV1(500)
for _, v := range ids {
	fmt.Println(v)
}

ids = make([]UUID, 100)
ReadV1(ids)
for _, v := range ids {
    fmt.Println(v)
}

// If you wish to register a saving mechanism to keep track of your UUIDs over restarts
// It is recommeneded to add a Saver so as to reduce risk in UUID collisions
saver := savers.FileSystemSaver.Init()

// Must be called before any V1 or V2 UUIDs. Do not call other uuid.Register* if
// registering a Saver
uuid.RegisterSaver(saver)

Version 3 and 5 UUIDs

import "gopkg.in/myesui/uuid.v1"

id := uuid.NewV3(uuid.NameSpaceURL, uuid.Name("www.example.com"))
fmt.Println(id)
fmt.Printf("version %s variant %x: %s\n", u1.Version(), u1.Variant(), id)

id := uuid.NewV5(uuid.NameSpaceURL, uuid.Name("www.example.com"))
fmt.Println(id)
fmt.Printf("version %s variant %x: %s\n", u1.Version(), u1.Variant(), id)

id = uuid.NewV5(uuid.NameSpaceURL, id)
fmt.Println(id)
fmt.Printf("version %s variant %x: %s\n", u1.Version(), u1.Variant(), id)

Version 4 UUIDs

import "gopkg.in/myesui/uuid.v1"

// A V4 UUID will panic by default if the systems CPRNG fails - this can
// be changed by registering your own generator
u4 := uuid.NewV4()
fmt.Println(id)
fmt.Printf("version %d variant %x: %s\n", u4.Version(), u4.Variant(), u4)

ids := uuid.BulkV4(500)
for _, v := range ids {
    fmt.Println(v)
}

ids := make([]UUID, 100)
ReadV4(ids)
for _, v := range ids {
    fmt.Println(v)
}

Custom Generators

import "gopkg.in/myesui/uuid.v1"

// Improve resolution for V1 and 2 UUIDs
// The resolution correlates to how many ids can be created before waiting
// for the next unique timestamp. The default is a low 1024, this equates
// to Ids that can be created in 100 nanoseconds. It is low to encourage
// you to set it.
uuid.RegisterGenerator(&GeneratorConfig{Resolution: 18465})

// Provide your own node Id or MAC address
uuid.RegisterGenerator(&GeneratorConfig{
    Id: func() uuid.Node{
        // My Node Id
        // If this returns nil a random one will be generated
    },
})

// Replace the default Timestamp spinner with your own.
uuid.RegisterGenerator(&GeneratorConfig{
    Next: func()(uuid.Timestamp){
        // My own Timestamp function...
        // Resolution will become reduendant if you set this.
        // The package will increment the clock sequence if you produce equal Timestamps
    },
})

// Replace the default crypto/rand.Read CPRNG with your own.
uuid.RegisterGenerator(&GeneratorConfig{
    Random: func([]byte)(int, error){
        // My CPRNG function...
    },
})

// type HandleRandomError func([]byte, int, error) error

// Replace the default random number error handler for V4 UUIDs. This function is called
// when there is an error in the crypto/rand CPRNG. The default error handler function reads 
// from math.Rand as a fallback.
// 
// You can change that behaviour and handle the error by providing your own function.
// 
// Errors could be due to a lack of system entropy or some other serious issue. These issues are rare,
// however, having the tools to handle such issues is important.
// This approach was taken as each user of this package will want to handle this differently.
// 
// For example one user of the package might want to just panic instead. 
//  Returning an error will cause a panic.

uuid.RegisterGenerator(&GeneratorConfig{
    HandleError: func(id []byte, n int, err error)bool{
        return err
    },
})

// You can also just generate your own completely.
myGenerator := NewGenerator(nil)

id := myGenerator.NewV4()

// You can replace the logger
uuid.RegisterGenerator(&GeneratorConfig{
        Logger: log.New(someWriter, "my-prefix", myFlags),
    })

Coverage

  • go test -coverprofile cover.out github.com/myesui/uuid

  • go test -coverprofile cover.out github.com/myesui/uuid/savers

  • go tool cover -html=cover.out -o cover.html

Contribution

  1. fork from the master branch to create your own fork
  2. clone from master into $GOPATH/src/github.com/myesui/uuid
  3. git remote add username https://github.com/username/uuid.git
  4. push changes on your fork and track your remote
  5. Remember to create a branch

To ensure you get the correct packages and subpackages install in a gopath which matches go/src/github.com/myesui/uuid

Design considerations

  • UUID is an interface which correlates to

  • V1 UUIDs are sequential. This can cause the Generator to work more slowly compared to other implementations. It can however be manually tuned to have performance that is on par. This is achieved by setting the Timestamp Resolution. Benchmark tests have been provided to help determine the best setting for your server

    Proper test coverage has determined thant the UUID timestamp spinner works correctly, across multiple clock resolutions. The generator produces timestamps that roll out sequentially and will only modify the clock sequence on very rare circumstances.

    It is highly recommended that you register a uuid.Saver if you use V1 or V2 UUIDs as it will ensure a higher probability of uniqueness.

      Example V1 output:
      5fb1a280-30f0-11e6-9614-005056c00001
      5fb1a281-30f0-11e6-9614-005056c00001
      5fb1a282-30f0-11e6-9614-005056c00001
      5fb1a283-30f0-11e6-9614-005056c00001
      5fb1a284-30f0-11e6-9614-005056c00001
      5fb1a285-30f0-11e6-9614-005056c00001
      5fb1a286-30f0-11e6-9614-005056c00001
      5fb1a287-30f0-11e6-9614-005056c00001
      5fb1a288-30f0-11e6-9614-005056c00001
      5fb1a289-30f0-11e6-9614-005056c00001
      5fb1a28a-30f0-11e6-9614-005056c00001
      5fb1a28b-30f0-11e6-9614-005056c00001
      5fb1a28c-30f0-11e6-9614-005056c00001
      5fb1a28d-30f0-11e6-9614-005056c00001
      5fb1a28e-30f0-11e6-9614-005056c00001
      5fb1a28f-30f0-11e6-9614-005056c00001
      5fb1a290-30f0-11e6-9614-005056c00001
    
  • The V1 UUID generator should be file system and server agnostic To achieve this there are: ** No Os locking threads or file system dependant storage ** Provided the uuid.Saver interface so a package can implement its own solution if required

  • The V4 UUID should allow a package to handle any error that can occur in the CPRNG. The default is to read from math.Rand``````.

  • The package should be able to handle multiple instances of Generators so a package can produce UUIDs from multiple sources.

Copyright (C) 2017 myesui@github.com See LICENSE file for details.

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

Examples

Constants

View Source
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

func RegisterSaver(saver Saver) (err error)

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

func (o *Generator) BulkV1(amount int) []UUID

BulkV1 will return a slice of V1 UUIDs. Be careful with the set amount.

func (*Generator) BulkV4 added in v1.0.0

func (o *Generator) BulkV4(amount int) []UUID

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

func (o *Generator) NewHash(hash hash.Hash, names ...interface{}) UUID

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

func (o *Generator) NewV1() UUID

NewV1 generates a new RFC4122 version 1 UUID based on a 60 bit timestamp and node id.

func (*Generator) NewV2

func (o *Generator) NewV2(idType SystemId) UUID

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

func (o *Generator) NewV4() (id UUID)

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.

func (*Generator) ReadV1 added in v1.0.0

func (o *Generator) ReadV1(ids []UUID)

ReadV1 will read a slice of UUIDs. Be careful with the set amount.

func (*Generator) ReadV4 added in v1.0.0

func (o *Generator) 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.

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

type HandleRandomError func([]byte, int, error) error

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

func (o Immutable) Bytes() []byte

Bytes return the underlying data representation of the Uuid in network byte order

func (Immutable) Size

func (o Immutable) Size() int

Size returns the octet length of the Uuid

func (Immutable) String

func (o Immutable) String() 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

func (o Immutable) UUID() UUID

UUID converts this implementation to the default type uuid.UUID

func (Immutable) Variant

func (o Immutable) Variant() uint8

Variant returns the implementation variant of the Uuid

func (Immutable) Version

func (o Immutable) Version() Version

Version returns the uuid.Version of the 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 Node

type Node []byte

Node represents the last node id setup used by the generator.

type Random

type Random func([]byte) (int, error)

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

type Store struct {
	Timestamp
	Sequence
	Node
}

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.

func (Store) String

func (o Store) String() string

String returns a string representation of the Store.

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.

const (
	SystemIdUser SystemId = iota + 1
	SystemIdEffectiveUser
	SystemIdGroup
	SystemIdEffectiveGroup
	SystemIdCallerProcess
	SystemIdCallerProcessParent
)

The following SystemId's are for use with V2 UUIDs.

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

func (Timestamp) Add

func (o Timestamp) Add(duration time.Duration) Timestamp

Add returns the timestamp as modified by the duration

func (Timestamp) String

func (o Timestamp) String() string

String Converts UUID Timestamp to time.Time and then calls the Stringer

func (Timestamp) Sub

func (o Timestamp) Sub(duration time.Duration) Timestamp

Sub returns the timestamp as modified by the duration

func (Timestamp) Time

func (o Timestamp) Time() time.Time

Time converts UUID Timestamp to UTC time.Time Note some higher clock resolutions will lose accuracy if above 100 ns ticks

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

func BulkV1(amount int) []UUID

BulkV1 will return a slice of V1 UUIDs. Be careful with the set amount.

func BulkV4 added in v1.0.0

func BulkV4(amount int) []UUID

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 New

func New(data []byte) UUID

New creates a UUID from a slice of bytes.

func NewHash added in v1.0.0

func NewHash(hash hash.Hash, names ...interface{}) UUID

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

func NewHex(uuid string) UUID

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

func NewV2(pDomain SystemId) UUID

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

func Parse(uuid string) (*UUID, error)

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) Bytes

func (o UUID) Bytes() []byte

Bytes return the underlying data representation of the Uuid.

func (UUID) MarshalBinary added in v1.0.0

func (o UUID) MarshalBinary() ([]byte, error)

MarshalBinary implements the encoding.BinaryMarshaler interface

func (UUID) MarshalText added in v1.0.0

func (o UUID) MarshalText() ([]byte, error)

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) Scan added in v1.0.0

func (o *UUID) Scan(src interface{}) error

Scan implements the sql.Scanner interface

func (UUID) Size

func (o UUID) Size() int

Size returns the octet length of the Uuid

func (UUID) String

func (o UUID) String() 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

func (o *UUID) UnmarshalBinary(bytes []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface

func (*UUID) UnmarshalText added in v1.0.0

func (o *UUID) UnmarshalText(uuid []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. It will support any text that MarshalText can produce.

func (UUID) Value added in v1.0.0

func (o UUID) Value() (value driver.Value, err error)

Value implements the driver.Valuer interface

func (UUID) Variant

func (o UUID) Variant() uint8

Variant returns the implementation variant of the Uuid

func (UUID) Version

func (o UUID) Version() Version

Version returns the uuid.Version of the Uuid

type Version

type Version int

Version represents the type of UUID.

const (
	VersionUnknown Version = iota // Unknown
	VersionOne                    // Time based
	VersionTwo                    // DCE security via POSIX UIDs
	VersionThree                  // Namespace hash uses MD5
	VersionFour                   // Crypto random
	VersionFive                   // Namespace hash uses SHA-1
)

The following are the supported Versions.

func (Version) String

func (o Version) String() string

String returns English description of version.

Directories

Path Synopsis
Package savers provides implementations for the uuid.Saver interface.
Package savers provides implementations for the uuid.Saver interface.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL