uuid

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2016 License: MIT Imports: 17 Imported by: 26

README

Go UUID implementation

license GoDoc Build Status Build Status Coverage Status

This project is currently pre 1.0.0

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

Any supported version of Go.

Design considerations

  • V1 UUIDs should be properly 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 work on all app servers To achieve this there are no Os locking threads or file system dependant storage. The uuid.Saver interface exists for the user to provide their own storage implementations. The package provides a uuid.Saver which works on a standard OS environment.

  • The V4 UUID should allow the user to choose how to handle any error that can occur in the CPRNG. The default is to panic.

  • The package should be able to handle multiple instances of Generator's so a

  • user can produce UUIDs from multiple sources.

Recent Changes

  • Added ability for user defined Generator's which can be setup with your own retrieval functions for a Node Id, Timestamp and Random data for a UUID; more details in docs.
  • Now builds in Windows, OsX and Linux, with test coverage checking and code quality checks.
  • Added V2 UUIDs
  • Improved builds and 100% test coverage
  • Library overhaul to cleanup exports that are not useful for a user
  • Improved and fixed file system uuid.Saver interface, breaking changes. To use a uuid.Saver make sure you pass it in via the uuid.RegisterSaver(Saver) function before a UUID is generated, so as to take affect. This is because only one attempt at system initialisation can be attempted.

Installation

Use the go tool:

$ go get github.com/twinj/uuid

Typical Usage

See documentation and examples for more information.

All UUIDs

import "github.com/twinj/uuid"

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)

Version 1 and 2 UUIDs

import "github.com/twinj/uuid"

// An uuid.Init or uuid.Register* function must be called before any V1 or
// V2 UUIDs, only needs 1 call.
uuid.Init()

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)

// If you wish to register a saving mechanism to keep track of your UUID
// It is recommeneded to add a Saver so as to reduce risk in UUID
// collisions
saver := new(savers.FileSystemSaver)
saver.Report = true
saver.Duration = time.Second * 3

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

Version 3 and 5 UUIDs

import "github.com/twinj/uuid"

// Does not need to be called first but is recommended
uuid.Init()

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 "github.com/twinj/uuid"

// Does not need to be called first but is recommended
uuid.Init()

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

Custom Generators

import "github.com/twinj/uuid"

// 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...
    },
})

// Replace the default error handler for V4 UUIDs. This function is called
// when there is an error in the CPRNG. The default function causes a panic.
// You can change that behaviour and handle the error by checking for nil
// on a NewV4() call.
//  id := NewV4()
//  if id == nil {
//      err := uuid.Error()
//      // handle error
//  }
// Trying again could fix the problem. 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.
uuid.RegisterGenerator(GeneratorConfig{
    HandleError: func(error)bool{
        // My HandleError function...
        // If this returns true the V4 generator will try again - if it
        //      fails again the NewV4() function will exit with a nil
        // If this returns false the NewV4() function will exit with a nil
    },
})

// You can also just manage your own completely.
gen := NewGenerator(GeneratorConfig{})

id := gen.NewV4()

Coverage

  • go test -coverprofile cover.out github.com/twinj/uuid
  • go tool cover -html=cover.out -o cover.html

Copyright (C) 2016 twinj@github.com See LICENSE file for details.

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

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
)

Variables

This section is empty.

Functions

func Compare

func Compare(pId, pId2 UUID) int

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 Equal

func Equal(p1, p2 UUID) bool

Compares whether each UUID is the same

func Formatter

func Formatter(pId UUID, pFormat Format) string

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

func Init

func Init() error

Init will initialise the default generator with default settings

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

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

func SwitchFormatToUpper

func SwitchFormatToUpper(pFormat Format)

SwitchFormatToUpper is a convenience function to set the Format to uppercase versions of the given constants.

Types

type Domain

type Domain uint8
const (
	DomainUser Domain = iota + 1
	DomainGroup
)

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

func (o *Generator) Error() (err error)

Error will return any error from the uuid.Generator if a UUID returns as Nil or nil

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(pDomain Domain) Uuid

NewV2 generates a new DCE version 2 UUID based on a 60 bit timestamp, node id and POSIX UID or GID

type GeneratorConfig

type GeneratorConfig struct {
	Saver
	Next
	Resolution uint
	Id
	Random
	HandleError
}

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

type HandleError func(error) bool

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

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

func (Name) String

func (o Name) String() string

String returns the uuid.Name as a string.

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

the last node id setup used by the generator

type Random

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

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

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

func (Timestamp) Add

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

Returns the timestamp as modified by the duration

func (Timestamp) String

func (o Timestamp) String() string

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

func (Timestamp) Sub

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

Returns the timestamp as modified by the duration

func (Timestamp) Time

func (o Timestamp) 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 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 New

func New(pData []byte) Uuid

New creates a UUID from a slice of bytes.

func NewHex

func NewHex(pUuid 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/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)
}

func NewV2

func NewV2(pDomain Domain) 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/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)
}

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

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

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

func Parse

func Parse(pUuid 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/twinj/uuid"
)

func main() {
	u, err := uuid.Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
	if err != nil {
		fmt.Println("error:", err)
	}
	fmt.Println(u)
}

func (Uuid) Bytes

func (o Uuid) Bytes() []byte

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

func (Uuid) MarshalBinary

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

MarshalBinary implements the encoding.BinaryMarshaler interface

func (Uuid) MarshalText

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

func (*Uuid) Scan

func (o *Uuid) Scan(pSrc 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

func (o *Uuid) UnmarshalBinary(pBytes []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface

func (*Uuid) UnmarshalText

func (o *Uuid) UnmarshalText(pUuid []byte) error

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

func (Uuid) Value

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 uint8

Version represents the type of UUID.

const (
	Unknown Version = iota // Unknown
	One                    // Time based
	Two                    // DCE security via POSIX UIDs
	Three                  // Namespace hash uses MD5
	Four                   // Crypto random
	Five                   // Namespace hash uses SHA-1
)

func (Version) String

func (o Version) String() string

String returns English description of version.

Directories

Path Synopsis
This package provides savers for the package github.com/twinj/uuid RFC4122 and DCE 1.1 UUIDs.
This package provides savers for the package github.com/twinj/uuid RFC4122 and DCE 1.1 UUIDs.

Jump to

Keyboard shortcuts

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