uuid

package
Version: v0.0.0-...-7f9930a Latest Latest
Warning

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

Go to latest
Published: Sep 6, 2015 License: MIT, Apache-2.0 Imports: 19 Imported by: 0

README

Go UUID implementation

Build Status GoDoc

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

  • Version 1: based on timestamp and MAC address
  • Version 3: based on MD5 hash
  • Version 4: based on cryptographically secure random numbers
  • Version 5: based on SHA-1 hash

Functions NewV1, NewV3, NewV4, NewV5, New, NewHex and Parse() for generating versions 3, 4 and 5 UUIDs are as specified in RFC 4122.

Requirements

Go 1.4, 1.3, 1.2 and tip supported.

Recent Changes

  • Removed use of OS Thread locking and runtime package requirement
  • Changed String() output to CleanHyphen to match the canonical standard
  • Plenty of minor change and housekeeping
  • Removed default saver and replaced with interface
  • API changes to simplify use.
  • Added formatting support for user defined formats
  • Added support for Google App Engine
  • Variant type bits are now set correctly
  • Variant type can now be retrieved more efficiently
  • New tests for variant setting to confirm correctness
  • New tests added to confirm proper version setting
  • Type UUID change to UUIDArray for V3-5 UUIDs and UUIDStruct added for V1 UUIDs ** These implement the BinaryMarshaller and BinaryUnmarshaller interfaces
  • New was added to create a base UUID from a []byte slice - this uses UUIDArray
  • ParseHex was renamed to ParseUUID
  • NewHex now performs unsafe creation of UUID from a hex string
  • NewV3 and NewV5 now take anything that implements the Stringer interface
  • V1 UUIDs can now be created
  • The printing format can be changed

Installation

Use the go tool:

$ go get github.com/twinj/uuid

Usage

See documentation and examples for more information.

var config = uuid.StateSaverConfig{SaveReport: true, SaveSchedule: 30 * time.Minute}
uuid.SetupFileSystemStateSaver(config)

u1 := uuid.NewV1()
uP, _ := uuid.Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
u3 := uuid.NewV3(uP, uuid.Name("test"))
u4 := uuid.NewV4()
fmt.Printf(print, u4.Version(), u4.Variant(), u4)

u5 := uuid.NewV5(uuid.NamespaceURL, uuid.Name("test"))

if uuid.Equal(u1, u3) {
	fmt.Printf("Will never happen")
}
fmt.Printf(uuid.Formatter(u5, uuid.CurlyHyphen))

uuid.SwitchFormat(uuid.BracketHyphen)

This is a derivative work

Orginal version from Copyright (C) 2011 by Krzysztof Kowalik chris@nu7hat.ch. See COPYING file for details.

Also see: Algorithm details in RFC 4122.

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

Documentation

Overview

This package provides RFC4122 UUIDs.

NewV1, NewV3, NewV4, NewV5, for generating versions 1, 3, 4 and 5 UUIDs as specified in RFC-4122.

New([]byte), unsafe; 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. I forked it but have since heavily redesigned it.

The example code in the specification was also used as reference for design.

Copyright (C) 2014 twinj@github.com 2014 MIT style licence

Example
package main

import (
	"fmt"
	"time"

	"github.com/twinj/uuid"
)

func main() {
	var config = uuid.StateSaverConfig{SaveReport: true, SaveSchedule: 30 * time.Minute}
	uuid.SetupFileSystemStateSaver(config)
	u1 := uuid.NewV1()
	fmt.Printf("version %d variant %x: %s\n", u1.Version(), u1.Variant(), u1)

	uP, _ := uuid.Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
	u3 := uuid.NewV3(uP, uuid.Name("test"))

	u4 := uuid.NewV4()
	fmt.Printf("version %d variant %x: %s\n", u4.Version(), u4.Variant(), u4)

	u5 := uuid.NewV5(uuid.NamespaceURL, uuid.Name("test"))

	if uuid.Equal(u1, u3) {
		fmt.Printf("Will never happen")
	}

	fmt.Printf(uuid.Formatter(u5, uuid.CurlyHyphen))

	uuid.SwitchFormat(uuid.BracketHyphen)
}
Output:

Index

Examples

Constants

View Source
const (
	ReservedNCS       byte = 0x00
	ReservedRFC4122   byte = 0x80 // or and A0 if masked with 1F
	ReservedMicrosoft byte = 0xC0
	ReservedFuture    byte = 0xE0
	TakeBack          byte = 0xF0
)

Variables

View Source
var (

	// The following standard UUIDs are for use with V3 or V5 UUIDs.
	NamespaceDNS  = &Struct{0x6ba7b810, 0x9dad, 0x11d1, 0x80, 0xb4, nodeId, length}
	NamespaceURL  = &Struct{0x6ba7b811, 0x9dad, 0x11d1, 0x80, 0xb4, nodeId, length}
	NamespaceOID  = &Struct{0x6ba7b812, 0x9dad, 0x11d1, 0x80, 0xb4, nodeId, length}
	NamespaceX500 = &Struct{0x6ba7b814, 0x9dad, 0x11d1, 0x80, 0xb4, nodeId, length}
)

Functions

func Digest

func Digest(o, pNs UUID, pName UniqueName, pHash hash.Hash)

Digest a namespace UUID and a UniqueName, which then marshals to a new UUID

func Equal

func Equal(p1 UUID, p2 UUID) bool

Compares whether each UUID is the same

func Formatter

func Formatter(pUUID UUID, pFormat Format) string

Format a UUID into a human readable string which matches the given Format Use this for one time formatting when setting the default using SwitchFormat is overkill.

Example
package main

import (
	"fmt"

	"github.com/twinj/uuid"
)

func main() {
	u4 := uuid.NewV4()
	fmt.Printf(uuid.Formatter(u4, uuid.CurlyHyphen))
}
Output:

func GetFormat

func GetFormat() string

Gets the current default format pattern

func Now

func Now() (sec int64, nsec int32)

TODO Create c version same as package runtime and time

func SetupCustomStateSaver

func SetupCustomStateSaver(pSaver StateSaver)

func SetupFileSystemStateSaver

func SetupFileSystemStateSaver(pConfig StateSaverConfig)
Example
package main

import (
	"fmt"
	"time"

	"github.com/twinj/uuid"
)

func main() {
	var config = uuid.StateSaverConfig{SaveReport: true, SaveSchedule: 30 * time.Minute}
	uuid.SetupFileSystemStateSaver(config)
	u1 := uuid.NewV1()
	fmt.Printf("version %d variant %x: %s\n", u1.Version(), u1.Variant(), u1)
}
Output:

func SwitchFormat

func SwitchFormat(pFormat Format)

Switches the default printing format for ALL UUID strings A valid format will have 6 groups if the supplied Format does not

Example
package main

import (
	"fmt"

	"github.com/twinj/uuid"
)

func main() {
	uuid.SwitchFormat(uuid.BracketHyphen)
	u4 := uuid.NewV4()
	fmt.Printf("version %d variant %x: %s\n", u4.Version(), u4.Variant(), u4)
}
Output:

func SwitchFormatUpperCase

func SwitchFormatUpperCase(pFormat Format)

Same as SwitchFormat but will make it uppercase

func UnmarshalBinary

func UnmarshalBinary(o UUID, pData []byte) error

Function provides a safe way to unmarshal bytes into an existing UUID. Checks for length.

Types

type Array

type Array [length]byte

A clean UUID type for simpler UUID versions

func (*Array) Bytes

func (o *Array) Bytes() []byte

func (Array) Format

func (o Array) Format(pFormat string) string

func (*Array) MarshalBinary

func (o *Array) MarshalBinary() ([]byte, error)

Marshals the UUID bytes into a slice

func (Array) Size

func (Array) Size() int

func (Array) String

func (o Array) String() string

func (*Array) Unmarshal

func (o *Array) Unmarshal(pData []byte)

func (*Array) UnmarshalBinary

func (o *Array) UnmarshalBinary(pData []byte) error

Un-marshals the data bytes into the UUID.

func (*Array) Variant

func (o *Array) Variant() byte

func (Array) Version

func (o Array) Version() int

type FileSystemSaver

type FileSystemSaver struct {
	// contains filtered or unexported fields
}

This implements the StateSaver interface for UUIDs

func (*FileSystemSaver) Init

func (o *FileSystemSaver) Init(pState *State)

func (*FileSystemSaver) Save

func (o *FileSystemSaver) Save(pState *State)

Saves the current state of the generator If the scheduled file save is reached then the file is synced

type Format

type Format string

A Format is a pattern used by the stringer interface with which to print the UUID.

const (
	Clean   Format = "%x%x%x%x%x%x"
	Curly   Format = "{%x%x%x%x%x%x}"
	Bracket Format = "(%x%x%x%x%x%x)"

	// This is the default format.
	CleanHyphen Format = "%x-%x-%x-%x%x-%x"

	CurlyHyphen   Format = "{%x-%x-%x-%x%x-%x}"
	BracketHyphen Format = "(%x-%x-%x-%x%x-%x)"
	GoIdFormat    Format = "[%X-%X-%x-%X%X-%x]"
)

type Name

type Name string

A UUID Name is a simple string which implements UniqueName which satisfies the Stringer interface.

func (Name) String

func (o Name) String() string

Returns the name as a string. Satisfies the Stringer interface.

type State

type State struct {
	sync.Mutex
	// contains filtered or unexported fields
}

Holds package information about the current state of the UUID generator

type StateSaver

type StateSaver interface {
	// Init is run if Setup() is false
	// Init should setup the system to save the state
	Init(*State)

	// Save saves the state and is called only if const V1Save and
	// Setup() is true
	Save(*State)
}

Use this interface to setup a custom state saver if you wish to have v1 UUIDs based on your node id and constant time.

type StateSaverConfig

type StateSaverConfig struct {

	// Print save log
	SaveReport bool

	// Save every x nanoseconds
	SaveSchedule time.Duration
}

A wrapper for default setup of the FileSystemStateSaver

type Struct

type Struct struct {
	// contains filtered or unexported fields
}

Struct is used for RFC4122 Version 1 UUIDs

func (*Struct) Bytes

func (o *Struct) Bytes() (data []byte)

func (Struct) Format

func (o Struct) Format(pFormat string) string

func (*Struct) MarshalBinary

func (o *Struct) MarshalBinary() ([]byte, error)

Marshals the UUID bytes into a slice

func (Struct) Size

func (o Struct) Size() int

func (Struct) String

func (o Struct) String() string

func (*Struct) Unmarshal

func (o *Struct) Unmarshal(pData []byte)

func (*Struct) UnmarshalBinary

func (o *Struct) UnmarshalBinary(pData []byte) error

Un-marshals the data bytes into the UUID struct. Implements the BinaryUn-marshaller interface

func (Struct) Variant

func (o Struct) Variant() byte

func (Struct) Version

func (o Struct) Version() int

type Timestamp

type Timestamp uint64

func (Timestamp) Unix

func (o Timestamp) Unix() time.Time

type UUID

type UUID interface {
	encoding.BinaryMarshaler
	encoding.BinaryUnmarshaler

	// Marshals the UUID bytes or data
	Bytes() (data []byte)

	// Organises data into a new UUID
	Unmarshal(pData []byte)

	// Size is used where different implementations require
	// different sizes. Should return the number of bytes in
	// the implementation.
	// Enables unmarshal and Bytes to screen for size
	Size() int

	// Version returns a version number of the algorithm used
	// to generate the UUID.
	// This may may behave independently across non RFC4122 UUIDs
	Version() int

	// Variant returns the UUID Variant
	// This will be one of the constants:
	// ReservedRFC4122,
	// ReservedMicrosoft,
	// ReservedFuture,
	// ReservedNCS.
	// This may behave differently across non RFC4122 UUIDs
	Variant() byte

	// UUID can be used as a Name within a namespace
	// Is simply just a String() string method
	// Returns a formatted version of the UUID.
	String() string
}

The main interface for UUIDs Each implementation must also implement the UniqueName interface

func New

func New(pData []byte) UUID

New creates a UUID from a slice of bytes. Truncates any bytes past the default length of 16 Will panic if data slice is too small.

func NewHex

func NewHex(pUuid string) UUID

Creates a UUID from a hex string Will panic if hex string is invalid - will panic even with hyphens and brackets Expects a clean string use Parse otherwise.

func NewV1

func NewV1() UUID

NewV1 will generate a new RFC4122 version 1 UUID

Example
package main

import (
	"fmt"

	"github.com/twinj/uuid"
)

const print = "version %d variant %x: %s\n"

func main() {
	u1 := uuid.NewV1()
	fmt.Printf(print, u1.Version(), u1.Variant(), u1)
}
Output:

func NewV3

func NewV3(pNs UUID, pName UniqueName) UUID

NewV3 will generate a new RFC4122 version 3 UUID V3 is based on the MD5 hash of a namespace identifier 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 will generate 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(pNs UUID, pName UniqueName) UUID

NewV5 will generate a new RFC4122 version 5 UUID Generate a UUID based on the SHA-1 hash of a namespace identifier and a 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

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

type UUIDVersion

type UUIDVersion int
const (
	NONE UUIDVersion = iota
	RFC4122v1
	DunnoYetv2
	RFC4122v3
	RFC4122v4
	RFC4122v5
)

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 IPs, URLs, the several Address types, Buffers and any other type which implements Stringer string, []byte types and Hash sums will need to be cast to the Name type or some other type which implements Stringer or UniqueName

func NewName

func NewName(salt string, pNames ...UniqueName) UniqueName

NewName will create a unique name from several sources

Jump to

Keyboard shortcuts

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