uu

package
v0.0.0-...-07f43dd Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2026 License: MIT Imports: 28 Imported by: 13

README

UUID package for Go language

Base on package github.com/satori/go.uuid

This package provides pure Go implementation of Universally Unique Identifier (UUID). Supported both creation and parsing of UUIDs.

With 100% test coverage and benchmarks out of box.

Supported versions:

  • Version 1, based on timestamp and MAC address (RFC 4122)
  • Version 2, based on timestamp, MAC address and POSIX UID/GID (DCE 1.1)
  • Version 3, based on MD5 hashing (RFC 4122)
  • Version 4, based on random numbers (RFC 4122)
  • Version 5, based on SHA-1 hashing (RFC 4122)

Installation

Use the go command:

go get github.com/domonda/go-types/uu

Example

package main

import (
    "fmt"
    "github.com/domonda/go-types/uu"
)

func main() {
    // Creating UUID Version 4
    u1 := uu.IDV4()
    fmt.Printf("UUIDv4: %s\n", u1)

    // Parsing UUID from string input
    u2, err := uu.IDFromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
    if err != nil {
        fmt.Printf("Something gone wrong: %s", err)
    }
    fmt.Printf("Successfully parsed: %s", u2)
}

Documentation

Documentation is hosted at GoDoc project.

Copyright (C) 2013-2016 by Maxim Bublis [email protected].

UUID package released under MIT License. See LICENSE for details.

Documentation

Index

Examples

Constants

View Source
const (
	IDVariantNCS = iota
	IDVariantRFC4122
	IDVariantMicrosoft
	IDVariantInvalid
)

UUID layout variants.

View Source
const (
	IDDomainPerson = iota
	IDDomainGroup
	IDDomainOrg
)

UUID DCE domains.

View Source
const (
	ErrNilID errs.Sentinel = "Nil UUID"

	ErrInvalidVariant errs.Sentinel = "invalid UUID variant"
)
View Source
const IDRegex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"

Variables

View Source
var (
	NamespaceDNS  = IDMustFromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
	NamespaceURL  = IDMustFromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8")
	NamespaceOID  = IDMustFromString("6ba7b812-9dad-11d1-80b4-00c04fd430c8")
	NamespaceX500 = IDMustFromString("6ba7b814-9dad-11d1-80b4-00c04fd430c8")
)

Predefined namespace UUIDs.

View Source
var IDvDefault = IDv7

IDvDefault is the default UUID version function used by NewID.

Functions

func ContextWithID

func ContextWithID(ctx context.Context, id ID, keys ...any) context.Context

ContextWithID adds an ID generating function to the context that will return the passed ID for the given keys or for the default key used by NewID if no keys are passed.

The function is a shortcut for ContextWithIDFunc(ctx, func() ID { return id }, keys...)

func ContextWithIDFunc

func ContextWithIDFunc(ctx context.Context, f func() ID, keys ...any) context.Context

ContextWithIDFunc adds an ID generating function to the context either for the passed keys, or for the default key used by NewID if no keys are passed.

func ContextWithIDSequence

func ContextWithIDSequence(ctx context.Context, key any, ids ...ID) context.Context

ContextWithIDSequence adds an ID generating function to the context that will return the passed IDs in the given order.

This function is intended to be used in tests to override random generation with a deterministic series using IDFromContext to retrieve the IDs with the given key.

func IDFuncFromContext

func IDFuncFromContext(ctx context.Context) func() ID

IDFuncFromContext returns the ID generating function from the context added with ContextWithIDFunc.

func IDv7DeterministicFunc

func IDv7DeterministicFunc(startAtUnixMilli int64) func() ID

IDv7DeterministicFunc returns a function that generates deterministic version 7 UUIDs starting at the passed Unix Epoch in milliseconds and counting up from there for every call of the returned function.

The returned function is safe for concurrent use.

func NullableIDCompare

func NullableIDCompare(a, b NullableID) int

NullableIDCompare returns bytes.Compare result of a and b.

Types

type ErrInvalidVersion

type ErrInvalidVersion int

func (ErrInvalidVersion) Error

func (e ErrInvalidVersion) Error() string

type ID

type ID [16]byte

ID is a UUID representation compliant with specification described in RFC 4122.

var IDNil ID

The nil UUID is special form of UUID that is specified to have all 128 bits set to zero: "00000000-0000-0000-0000-000000000000"

func IDFrom

func IDFrom[T IDSource](val T) ID

IDFrom converts val to an ID or returns IDNil if the conversion is not possible. The returned ID is not validated.

Supported types (via IDSource constraint):

  • string: parsed using IDFromStringOrNil (supports all format variations)
  • []byte: parsed using IDFromBytesOrNil (supports all format variations)
  • ID, NullableID, [16]byte: directly converted

For string and []byte inputs, supports:

  • Binary format (16 bytes for []byte only)
  • Base64 URL encoding (22 chars/bytes)
  • Hex without dashes (32 chars/bytes)
  • Standard dashed format (36 chars/bytes)
  • URN format with "urn:uuid:" prefix
  • Optional surrounding quotes "" or braces {}

func IDFromAny

func IDFromAny(val any) (ID, error)

IDFromAny converts val to an ID or returns an error if the conversion is not possible or the ID is not valid.

Supported types:

  • string: parsed using IDFromString (supports all format variations)
  • []byte: parsed using IDFromBytes (supports all format variations)
  • ID, NullableID, [16]byte: validated and converted
  • nil: returns IDNil with ErrNilID

For string and []byte inputs, supports:

  • Binary format (16 bytes for []byte only)
  • Base64 URL encoding (22 chars/bytes)
  • Hex without dashes (32 chars/bytes)
  • Standard dashed format (36 chars/bytes)
  • URN format with "urn:uuid:" prefix
  • Optional surrounding quotes "" or braces {}

func IDFromBytes

func IDFromBytes(b []byte) (ID, error)

IDFromBytes parses a byte slice as UUID supporting multiple formats:

Binary format (16 bytes):

  • Raw 16-byte UUID representation

String formats (after removing optional surrounding quotes "" or braces {}):

  • 22 bytes: Base64 URL encoding without padding (e.g., "abcdefghijklmnopqrstuv")
  • 32 bytes: Hex encoding without dashes (e.g., "6ba7b8109dad11d180b400c04fd430c8")
  • 36 bytes: Standard dashed format (e.g., "6ba7b810-9dad-11d1-80b4-00c04fd430c8")
  • URN format: "urn:uuid:" prefix followed by 36-byte dashed format

The function automatically strips surrounding double quotes or braces before parsing.

func IDFromBytesOrNil

func IDFromBytesOrNil(s []byte) ID

IDFromBytesOrNil parses a byte slice as UUID supporting multiple formats. Same behavior as IDFromBytes, but returns IDNil on error instead of returning an error.

Supports all formats documented in IDFromBytes:

  • Binary format (16 bytes)
  • Base64 URL encoding (22 bytes)
  • Hex without dashes (32 bytes)
  • Standard dashed format (36 bytes)
  • URN format with "urn:uuid:" prefix
  • Optional surrounding quotes "" or braces {}

func IDFromContext

func IDFromContext(ctx context.Context, key any) ID

IDFromContext returns the ID that was added to the context with the passed key, or the result of IDvDefault() if no ID was added.

This function enables writing tests with predefined IDs that are passed through from the test via the context, and falling back to the default ID generation for non-testing environments.

func IDFromPtr

func IDFromPtr(ptr *ID, defaultVal ID) ID

IDFromPtr returns the dereferenced value of ptr, or defaultVal if ptr is nil.

func IDFromString

func IDFromString(s string) (ID, error)

IDFromString parses a string as UUID supporting multiple formats:

After removing optional surrounding quotes "" or braces {}:

  • 22 characters: Base64 URL encoding without padding (e.g., "abcdefghijklmnopqrstuv")
  • 32 characters: Hex encoding without dashes (e.g., "6ba7b8109dad11d180b400c04fd430c8")
  • 36 characters: Standard dashed format (e.g., "6ba7b810-9dad-11d1-80b4-00c04fd430c8")
  • URN format: "urn:uuid:" prefix followed by 36-character dashed format

Examples of valid inputs:

  • "6ba7b8109dad11d180b400c04fd430c8" (hex without dashes)
  • "6ba7b810-9dad-11d1-80b4-00c04fd430c8" (standard dashed)
  • "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}" (braces with dashed)
  • "\"6ba7b810-9dad-11d1-80b4-00c04fd430c8\"" (quoted dashed)
  • "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8" (URN format)
  • "a3fW6RxSR_amqRvJxqIi2g" (base64 URL encoding)

The function automatically strips surrounding double quotes or braces before parsing.

func IDFromStringOrNil

func IDFromStringOrNil(input string) ID

IDFromStringOrNil parses a string as UUID supporting multiple formats, or returns IDNil in case of a parsing error.

Supports all formats documented in IDFromString:

  • 22 characters: Base64 URL encoding without padding
  • 32 characters: Hex encoding without dashes
  • 36 characters: Standard dashed format
  • URN format: "urn:uuid:" prefix followed by dashed format
  • Optional surrounding quotes "" or braces {}

func IDHash

func IDHash(h hash.Hash, namespace ID, data []byte, version int) (id ID)

IDHash returns a UUID based on hashing of namespace UUID and data within that namespace.

func IDMust

func IDMust[T IDSource](val T) ID

IDMust converts val to an ID or panics if the conversion is not possible or the ID is not valid.

Supported types (via IDSource constraint):

  • string: parsed using IDFromString (supports all format variations)
  • []byte: parsed using IDFromBytes (supports all format variations)
  • ID, NullableID, [16]byte: validated and converted

For string and []byte inputs, supports:

  • Binary format (16 bytes for []byte only)
  • Base64 URL encoding (22 chars/bytes)
  • Hex without dashes (32 chars/bytes)
  • Standard dashed format (36 chars/bytes)
  • URN format with "urn:uuid:" prefix
  • Optional surrounding quotes "" or braces {}

func IDMustFromString

func IDMustFromString(input string) ID

IDMustFromString parses a string as UUID supporting multiple formats. Panics if there is an error.

Supports all formats documented in IDFromString:

  • 22 characters: Base64 URL encoding without padding
  • 32 characters: Hex encoding without dashes
  • 36 characters: Standard dashed format
  • URN format: "urn:uuid:" prefix followed by dashed format
  • Optional surrounding quotes "" or braces {}

func IDv1

func IDv1() (id ID)

IDv1 returns a version 1 ID based on current timestamp and MAC address.

func IDv2

func IDv2(domain byte) (id ID)

IDv2 returns a version 2 DCE Security UUID based on POSIX UID/GID.

func IDv3

func IDv3(namespace ID, data []byte) ID

IDv3 returns a version 3 UUID based on MD5 hash of the namespace UUID and name.

func IDv4

func IDv4() (id ID)

IDv4 returns a version 4 random generated UUID.

func IDv5

func IDv5(namespace ID, data []byte) ID

IDv5 returns a version 5 UUID based on SHA-1 hash of the namespace UUID and data.

func IDv7

func IDv7() ID

IDv7 returns a version 7 ID with the first 48 bits containing a sortable timestamp and random data after the version and variant information.

func IDv7Deterministic

func IDv7Deterministic(unixMilli int64) ID

IDv7Deterministic returns a version 7 ID with the first 48 bits containing passed unixMilli timestamp and no random data.

Intended for generating deterministic UUIDs for testing, see also IDv7DeterministicFunc.

func IDv7WithTime

func IDv7WithTime(t time.Time) ID

IDv7WithTime returns a version 7 ID with the first 48 bits containing a sortable timestamp created from the passed time and random data after the version and variant information.

Note that the precision is only milliseconds.

See ID.V7Time for the reverse operation.

func NewID

func NewID(ctx context.Context) ID

NewID returns a UUID generated with IDvDefault if the context does not have a function added to it with ContextWithIDFunc, else the context function is used.

The context function can be used to override random generation with a deterministic series for testing.

See also IDv7Deterministic and IDv7DeterministicFunc.

func (ID) Base64

func (id ID) Base64() string

Base64 returns the unpadded base64 URL encoding of the UUID. The returned string is always 22 characters long.

func (ID) Bytes

func (id ID) Bytes() []byte

Bytes returns bytes slice representation of UUID.

func (ID) GoString

func (id ID) GoString() string

GoString returns a pseudo Go literal for the ID in the format:

uu.IDFrom(`xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`)

func (ID) Hex

func (id ID) Hex() string

Hex returns the hex representation without dashes of the UUID The returned string is always 32 characters long.

func (ID) IsNil

func (id ID) IsNil() bool

IsNil returns if the id is the Nil UUID value (all zeros)

func (ID) IsNotNil

func (id ID) IsNotNil() bool

IsNotNil returns if the id is not the Nil UUID value (all zeros)

func (ID) IsZero

func (id ID) IsZero() bool

IsZero returns if the id is the Nil UUID value (all zeros)

func (ID) JSONSchema

func (ID) JSONSchema() *jsonschema.Schema
Example
reflector := jsonschema.Reflector{DoNotReference: true}
schema, _ := json.MarshalIndent(reflector.Reflect(ID{}), "", "  ")
fmt.Println(string(schema))
Output:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://github.com/domonda/go-types/uu/id",
  "type": "string",
  "format": "uuid",
  "title": "UUID"
}

func (ID) Less

func (id ID) Less(rhs ID) bool

Less returns true if the 128 bit unsigned integer value of the id is less than the passed rhs.

func (ID) MarshalBinary

func (id ID) MarshalBinary() (data []byte, err error)

MarshalBinary implements the encoding.BinaryMarshaler interface.

func (ID) MarshalText

func (id ID) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface. The encoding is the same as returned by String.

func (ID) Nullable

func (id ID) Nullable() NullableID

Nullable returns the ID as NullableID

func (ID) PrettyPrint

func (id ID) PrettyPrint(w io.Writer)

PrettyPrint the ID in the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. Implements the pretty.Printable interface.

func (*ID) Scan

func (id *ID) Scan(src any) error

Scan implements the sql.Scanner interface. A 16-byte slice is handled by UnmarshalBinary, while a longer byte slice or a string is handled by UnmarshalText.

func (*ID) SetVariant

func (id *ID) SetVariant()

SetVariant sets variant bits as described in RFC 4122.

func (*ID) SetVersion

func (id *ID) SetVersion(v int)

SetVersion sets version bits.

func (ID) String

func (id ID) String() string

String returns the canonical string representation of the UUID:

xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

String implements the fmt.Stringer interface.

func (ID) StringBytes

func (id ID) StringBytes() []byte

StringBytes returns the canonical string representation of the UUID as byte slice: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

func (ID) StringUpper

func (id ID) StringUpper() string

StringUpper returns the upper case version of the canonical string format:

XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX

func (*ID) UnmarshalBinary

func (id *ID) UnmarshalBinary(data []byte) (err error)

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. It will return error if the slice isn't 16 bytes long, but does not check the validity of the UUID.

func (*ID) UnmarshalText

func (id *ID) UnmarshalText(text []byte) (err error)

UnmarshalText implements the encoding.TextUnmarshaler interface. Supports the same formats as IDFromBytes:

Binary format (16 bytes):

  • Raw 16-byte UUID representation

String formats (after removing optional surrounding quotes "" or braces {}):

  • 22 bytes: Base64 URL encoding without padding (e.g., "abcdefghijklmnopqrstuv")
  • 32 bytes: Hex encoding without dashes (e.g., "6ba7b8109dad11d180b400c04fd430c8")
  • 36 bytes: Standard dashed format (e.g., "6ba7b810-9dad-11d1-80b4-00c04fd430c8")
  • URN format: "urn:uuid:" prefix followed by 36-byte dashed format

Examples of valid inputs:

  • `6ba7b8109dad11d180b400c04fd430c8` (hex without dashes)
  • `6ba7b810-9dad-11d1-80b4-00c04fd430c8` (standard dashed)
  • `{6ba7b810-9dad-11d1-80b4-00c04fd430c8}` (braces with dashed)
  • `"6ba7b810-9dad-11d1-80b4-00c04fd430c8"` (quoted dashed)
  • `urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8` (URN format)
  • `a3fW6RxSR_amqRvJxqIi2g` (base64 URL encoding)

The function automatically strips surrounding double quotes or braces before parsing.

func (ID) V7Time

func (id ID) V7Time() time.Time

V7Time returns the timestamp of a version 7 UUID. If the UUID is not a version 7 UUID, a zero time is returned.

Note that the precision is only milliseconds.

See IDv7WithTime for the reverse operation.

func (ID) Valid

func (id ID) Valid() bool

Valid returns if Variant and Version of this UUID are supported. A Nil UUID is not valid.

func (ID) Validate

func (id ID) Validate() error

Validate returns an error if the Variant and Version of this UUID are not supported. A Nil UUID is not valid.

func (ID) Value

func (id ID) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

func (ID) Variant

func (id ID) Variant() int

Variant returns an ID layout variant or IDVariantInvalid if unknown.

func (ID) Version

func (id ID) Version() int

Version returns algorithm version used to generate UUID.

type IDMutex

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

IDMutex manages a unique mutex for every locked UUID key. The mutex for a key exists as long as there are any locks waiting to be unlocked. This is equivalent to declaring a mutex variable for every key, except that the key and the number of mutexes are dynamic.

func NewIDMutex

func NewIDMutex() *IDMutex

NewIDMutex returns a new IDMutex

func NewIDMutexWithCallbacks

func NewIDMutexWithCallbacks(onLock, onUnlock func(ID)) *IDMutex

NewIDMutexWithCallbacks returns a new IDMutex where the passed functions are called back as first operation from Lock and Unlock before any any locking or unlocking. Usable for debugging and logging.

func (*IDMutex) IsLocked

func (m *IDMutex) IsLocked(id ID) bool

IsLocked tells wether an ID is locked.

func (*IDMutex) Lock

func (m *IDMutex) Lock(id ID)

Lock the mutex for a given ID.

func (*IDMutex) Unlock

func (m *IDMutex) Unlock(id ID)

Unlock the mutex for a given ID.

type IDSet

type IDSet map[ID]struct{}

IDSet is a set of uu.IDs. It is a map[ID]struct{} underneath. Implements the database/sql.Scanner and database/sql/driver.Valuer interfaces with the nil map value used as SQL NULL

func IDSetFromString

func IDSetFromString(str string) (IDSet, error)

IDSetFromString parses a string created with IDSet.String()

func IDSetMust

func IDSetMust[T IDSource](vals ...T) IDSet

IDSetMust converts the passed values to an IDSet or panics if that's not possible or an ID is not valid. Returns nil if zero values are passed.

func MakeIDSet

func MakeIDSet(ids ...ID) IDSet

MakeIDSet returns an IDSet with the optional passed ids added to it.

func MakeIDSetFromStrings

func MakeIDSetFromStrings(strs []string) (IDSet, error)

MakeIDSetFromStrings returns an IDSet with strs parsed as IDs

func MakeIDSetMustFromStrings

func MakeIDSetMustFromStrings(strs ...string) IDSet

MakeIDSetMustFromStrings returns an IDSet with the passed strings as IDs or panics if there was an error.

func (IDSet) Add

func (s IDSet) Add(id ID)

func (IDSet) AddIDs

func (s IDSet) AddIDs(ids IDs)

func (IDSet) AddSet

func (s IDSet) AddSet(other IDSet)

func (IDSet) AddSlice

func (set IDSet) AddSlice(s IDSlice)

func (IDSet) AsSet

func (s IDSet) AsSet() IDSet

AsSet returns s unchanged to implement the IDs interface.

func (IDSet) AsSlice

func (s IDSet) AsSlice() IDSlice

AsSlice returns the IDs of the set as IDSlice with undefined order.

func (IDSet) AsSortedSlice

func (s IDSet) AsSortedSlice() IDSlice

AsSortedSlice returns the IDs of the set as sorted IDSlice.

func (IDSet) Clear

func (s IDSet) Clear()

func (IDSet) Clone

func (s IDSet) Clone() IDSet

func (IDSet) Contains

func (s IDSet) Contains(id ID) bool

Contains returns true if the set contains the passed id. It is valid to call this method on a nil IDSet.

func (IDSet) Delete

func (s IDSet) Delete(id ID)

func (IDSet) DeleteSet

func (s IDSet) DeleteSet(other IDSet)

func (IDSet) DeleteSlice

func (s IDSet) DeleteSlice(sl IDSlice)

func (IDSet) Diff

func (s IDSet) Diff(other IDSet) IDSet

func (IDSet) Equal

func (s IDSet) Equal(other IDSet) bool

func (IDSet) ForEach

func (s IDSet) ForEach(callback func(ID) error) error

ForEach calls the passed function for each ID. Any error from the callback function is returned by ForEach immediatly. Returning a sentinel error is a way to stop the loop with a known cause that might not be a real error.

func (IDSet) GetOne

func (s IDSet) GetOne() ID

GetOne returns one ID in undefined order from the set or IDNil if the set is empty. Most useful to get the only ID in a set of size one.

func (IDSet) IsEmpty

func (s IDSet) IsEmpty() bool

IsEmpty returns true if the set is empty or nil.

func (IDSet) IsNull

func (s IDSet) IsNull() bool

IsNull implements the nullable.Nullable interface by returning true if the set is nil.

func (IDSet) Len

func (s IDSet) Len() int

Len returns the length of the IDSet.

func (IDSet) MarshalJSON

func (s IDSet) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler

func (IDSet) MarshalText

func (s IDSet) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface

func (IDSet) PrettyPrint

func (s IDSet) PrettyPrint(w io.Writer)

PrettyPrint using s.AsSortedSlice().PrettyPrint(w). Implements the pretty.Printable interface.

func (*IDSet) Scan

func (s *IDSet) Scan(value any) error

Scan implements the database/sql.Scanner interface with the nil map value used as SQL NULL. Id does assign a new IDSet to *set instead of modifying the existing map, so it can be used with uninitialized IDSet variable.

func (IDSet) String

func (s IDSet) String() string

String implements the fmt.Stringer interface.

func (IDSet) Strings

func (s IDSet) Strings() []string

Strings returns a slice with all IDs converted to strings

func (*IDSet) UnmarshalJSON

func (s *IDSet) UnmarshalJSON(data []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler Id does assign a new IDSet to *set instead of modifying the existing map, so it can be used with uninitialized IDSet variable.

func (*IDSet) UnmarshalText

func (s *IDSet) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface

func (IDSet) Value

func (s IDSet) Value() (driver.Value, error)

Value implements the driver database/sql/driver.Valuer interface with the nil map value used as SQL NULL

type IDSlice

type IDSlice []ID

IDSlice is a slice of uu.IDs. It is a []ID underneath. Implements the database/sql.Scanner and database/sql/driver.Valuer interfaces. Implements the encoding/json.Marshaler and Unmarshaler interfaces. with the nil slice value used as SQL NULL and JSON null.

func IDSliceFromString

func IDSliceFromString(str string) (IDSlice, error)

IDSliceFromString parses a string created with IDSlice.String()

func IDSliceFromStrings

func IDSliceFromStrings(strs []string) (IDSlice, error)

IDSliceFromStrings parses an IDSlice from strings

func IDSliceMust

func IDSliceMust[T IDSource](vals ...T) IDSlice

IDSliceMust converts the passed values to an IDSlice or panics if that's not possible or an ID is not valid. Returns nil if zero values are passed.

func IDSliceMustFromStrings

func IDSliceMustFromStrings(strs ...string) IDSlice

IDSliceMustFromStrings parses an IDSlice from strings and panics in case of an error.

func (IDSlice) AsSet

func (s IDSlice) AsSet() IDSet

AsSet returns the IDs of the slice as a IDSet.

func (IDSlice) AsSlice

func (s IDSlice) AsSlice() IDSlice

AsSlice returns s unchanged to implement the IDs interface.

func (IDSlice) Clone

func (s IDSlice) Clone() IDSlice

Clone returns a copy of the slice.

func (IDSlice) Contains

func (s IDSlice) Contains(id ID) bool

func (IDSlice) ContainsAny

func (s IDSlice) ContainsAny(other IDSlice) bool

func (IDSlice) ContainsAnyFromSet

func (s IDSlice) ContainsAnyFromSet(set IDSet) bool

func (IDSlice) Equal

func (s IDSlice) Equal(other IDSlice) bool

func (IDSlice) ForEach

func (s IDSlice) ForEach(callback func(ID) error) error

ForEach calls the passed function for each ID. Any error from the callback function is returned by ForEach immediatly. Returning a sentinel error is a way to stop the loop with a known cause that might not be a real error.

func (IDSlice) IndexOf

func (s IDSlice) IndexOf(id ID) int

IndexOf returns the index of the first occurrence of id in the slice, or -1 if id was not found.

func (IDSlice) Len

func (s IDSlice) Len() int

Len is the number of elements in the collection. One of the methods to implement sort.Interface.

func (IDSlice) Less

func (s IDSlice) Less(i, j int) bool

Less reports whether the element with index i should sort before the element with index j. One of the methods to implement sort.Interface.

func (IDSlice) MarshalJSON

func (s IDSlice) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler

func (IDSlice) MarshalText

func (s IDSlice) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface

func (IDSlice) PrettyPrint

func (s IDSlice) PrettyPrint(w io.Writer)

PrettyPrint using IDSlice.String(). Implements the pretty.Printable interface.

func (IDSlice) Raw

func (s IDSlice) Raw() [][16]byte

Raw returns the underlying slice of [16]byte IDs. The returned slice is not a copy but a pointer to the original slice. The returned slice is not thread safe and should not be modified.

func (*IDSlice) RemoveAll

func (s *IDSlice) RemoveAll(id ID) (count int)

RemoveAll removes the all occurrences of id from the slice and returns the count of removals.

func (*IDSlice) RemoveAt

func (s *IDSlice) RemoveAt(index int)

RemoveAt removes the slice element at the given index. Will panic if the index is out of range.

func (*IDSlice) RemoveFirst

func (s *IDSlice) RemoveFirst(id ID) int

RemoveFirst removes the first occurrence of id from the slice and returns its index or -1 if id was not found in the slice.

func (*IDSlice) Scan

func (s *IDSlice) Scan(value any) (err error)

Scan implements the database/sql.Scanner interface with the nil map value used as SQL NULL. Does *s = make(Slice) if *s == nil so it can be used with an not initialized Slice variable

func (IDSlice) Sort

func (s IDSlice) Sort()

Sort the slice in place.

func (IDSlice) SortedClone

func (s IDSlice) SortedClone() IDSlice

SortedClone returns a sorted clone of the slice.

func (IDSlice) String

func (s IDSlice) String() string

String implements the fmt.Stringer interface.

func (IDSlice) Strings

func (s IDSlice) Strings() []string

Strings returns a slice with all IDs converted to strings

func (IDSlice) Swap

func (s IDSlice) Swap(i, j int)

Swap swaps the elements with indexes i and j. One of the methods to implement sort.Interface.

func (*IDSlice) UnmarshalJSON

func (s *IDSlice) UnmarshalJSON(data []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler

func (*IDSlice) UnmarshalText

func (s *IDSlice) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface by calling IDSliceFromString.

func (IDSlice) Value

func (s IDSlice) Value() (driver.Value, error)

Value implements the driver database/sql/driver.Valuer interface with the nil map value used as SQL NULL

type IDSource

type IDSource interface {
	string | []byte | ID | NullableID | [16]byte
}

type IDs

type IDs interface {
	fmt.Stringer
	pretty.Printable
	driver.Valuer
	json.Marshaler

	// Len returns the length of the ID collection.
	Len() int

	// AsSet returns the contained IDs as IDSet.
	AsSet() IDSet

	// AsSlice returns the contained IDs as IDSlice.
	AsSlice() IDSlice

	// Strings returns a slice with all IDs converted to strings
	Strings() []string

	// ForEach calls the passed function for each ID.
	// Any error from the callback function is returned
	// by ForEach immediatly.
	// Returning a sentinel error is a way to stop the loop
	// with a known cause that might not be a real error.
	ForEach(func(ID) error) error
}

IDs is an interface implemented by IDSet and IDSlice as abstract collection of IDs. It is intended for passing IDs as input arguments, but does not support scanning or unmarshalling.

type NullableID

type NullableID [16]byte

NullableID is a UUID where the Nil UUID "00000000-0000-0000-0000-000000000000" is interpreted as the null values for SQL and JSON.

var IDNull NullableID

IDNull is a zero UUID and will be treatet as SQL NULL.

func NullableIDFromAny

func NullableIDFromAny(val any) (NullableID, error)

NullableIDFromAny converts val to a NullableID or returns an error if the conversion is not possible or the ID is not valid.

Supported types:

  • string: parsed using NullableIDFromString (supports all format variations)
  • []byte: parsed using NullableIDFromBytes (supports all format variations)
  • ID, NullableID, [16]byte: validated and converted
  • nil: returns IDNull with no error

For string and []byte inputs, supports:

  • Binary format (16 bytes for []byte only)
  • Base64 URL encoding (22 chars/bytes)
  • Hex without dashes (32 chars/bytes)
  • Standard dashed format (36 chars/bytes)
  • URN format with "urn:uuid:" prefix
  • Optional surrounding quotes "" or braces {}

The Nil UUID "00000000-0000-0000-0000-000000000000" is interpreted as NULL.

func NullableIDFromBytes

func NullableIDFromBytes(s []byte) (NullableID, error)

NullableIDFromBytes parses a byte slice as UUID supporting multiple formats:

Binary format (16 bytes):

  • Raw 16-byte UUID representation

String formats (after removing optional surrounding quotes "" or braces {}):

  • 22 bytes: Base64 URL encoding without padding (e.g., "abcdefghijklmnopqrstuv")
  • 32 bytes: Hex encoding without dashes (e.g., "6ba7b8109dad11d180b400c04fd430c8")
  • 36 bytes: Standard dashed format (e.g., "6ba7b810-9dad-11d1-80b4-00c04fd430c8")
  • URN format: "urn:uuid:" prefix followed by 36-byte dashed format

The Nil UUID "00000000-0000-0000-0000-000000000000" is interpreted as NULL. See IDFromBytes for more details.

func NullableIDFromPtr

func NullableIDFromPtr(ptr *ID) NullableID

NullableIDFromPtr returns the dereferenced ID as NullableID if ptr is not nil, or returns IDNull if ptr is nil.

Note: A non-nil pointer to the Nil UUID "00000000-0000-0000-0000-000000000000" will be returned as IDNull (null), not as a valid NullableID containing the Nil UUID.

func NullableIDFromString

func NullableIDFromString(s string) (NullableID, error)

NullableIDFromString parses a string as NullableID supporting multiple formats:

After removing optional surrounding quotes "" or braces {}:

  • 22 characters: Base64 URL encoding without padding (e.g., "abcdefghijklmnopqrstuv")
  • 32 characters: Hex encoding without dashes (e.g., "6ba7b8109dad11d180b400c04fd430c8")
  • 36 characters: Standard dashed format (e.g., "6ba7b810-9dad-11d1-80b4-00c04fd430c8")
  • URN format: "urn:uuid:" prefix followed by 36-character dashed format

The Nil UUID "00000000-0000-0000-0000-000000000000" is interpreted as NULL. See IDFromString for more format examples.

func NullableIDFromStringOrNull

func NullableIDFromStringOrNull(s string) NullableID

NullableIDFromStringOrNull parses a string as UUID supporting multiple formats, or returns IDNull in case of a parsing error.

Supports the same formats as NullableIDFromString:

  • 22 characters: Base64 URL encoding without padding
  • 32 characters: Hex encoding without dashes
  • 36 characters: Standard dashed format
  • URN format: "urn:uuid:" prefix followed by dashed format
  • Optional surrounding quotes "" or braces {}

The Nil UUID "00000000-0000-0000-0000-000000000000" is interpreted as NULL.

func NullableIDMust

func NullableIDMust[T IDSource](val T) NullableID

NullableIDMust converts val to a NullableID or panics if the conversion is not possible or the ID is not valid.

Supported types (via IDSource constraint):

  • string: parsed using NullableIDFromString (supports all format variations)
  • []byte: parsed using NullableIDFromBytes (supports all format variations)
  • ID, NullableID, [16]byte: validated and converted

For string and []byte inputs, supports:

  • Binary format (16 bytes for []byte only)
  • Base64 URL encoding (22 chars/bytes)
  • Hex without dashes (32 chars/bytes)
  • Standard dashed format (36 chars/bytes)
  • URN format with "urn:uuid:" prefix
  • Optional surrounding quotes "" or braces {}

The Nil UUID "00000000-0000-0000-0000-000000000000" is interpreted as NULL.

func (NullableID) Base64

func (n NullableID) Base64() string

Base64 returns the unpadded base64 URL encoding of the UUID. The returned string is always 22 characters long.

func (NullableID) Get

func (n NullableID) Get() ID

Get returns the non nullable ID value or panics if the NullableID is null. Note: check with IsNull before using Get!

func (NullableID) GetOr

func (n NullableID) GetOr(defaultID ID) ID

GetOr returns the non nullable ID value or defaultID if the NullableID is null.

func (NullableID) GetOrNil

func (n NullableID) GetOrNil() ID

GetOrNil returns the non nullable ID value or the Nil UUID if n is null. Use Get to ensure getting a non Nil UUID or panic.

func (NullableID) GoString

func (n NullableID) GoString() string

GoString returns a pseudo Go literal for the ID in the format:

uu.NullableID(`xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`)

func (NullableID) Hex

func (n NullableID) Hex() string

Hex returns the hex representation without dashes of the UUID The returned string is always 32 characters long.

func (NullableID) IsNotNull

func (n NullableID) IsNotNull() bool

IsNotNull returns true if the NullableID is not null.

func (NullableID) IsNull

func (n NullableID) IsNull() bool

IsNull returns true if the NullableID is null. IsNull implements the nullable.Nullable interface.

func (NullableID) JSONSchema

func (NullableID) JSONSchema() *jsonschema.Schema
Example
reflector := jsonschema.Reflector{
	Anonymous:      true,
	DoNotReference: true,
}
schema, _ := json.MarshalIndent(reflector.Reflect(NullableID{}), "", "  ")
fmt.Println(string(schema))
Output:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "oneOf": [
    {
      "type": "string",
      "format": "uuid"
    },
    {
      "type": "null"
    }
  ],
  "title": "Nullable UUID",
  "default": null
}

func (NullableID) MarshalBinary

func (n NullableID) MarshalBinary() (data []byte, err error)

MarshalBinary implements the encoding.BinaryMarshaler interface.

func (NullableID) MarshalJSON

func (n NullableID) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (NullableID) MarshalText

func (n NullableID) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler. It will encode a blank string when this String is null.

func (NullableID) PrettyPrint

func (n NullableID) PrettyPrint(w io.Writer)

PrettyPrint the NullableID in the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx or as NULL. Implements the pretty.Printable interface.

func (NullableID) Ptr

func (n NullableID) Ptr() *ID

Ptr returns a pointer to this NullableID's value, or a nil pointer if this NullableID is null.

func (*NullableID) Scan

func (n *NullableID) Scan(src any) error

Scan implements the sql.Scanner interface.

func (*NullableID) Set

func (n *NullableID) Set(id ID)

Set sets an ID for this NullableID

func (*NullableID) SetNull

func (n *NullableID) SetNull()

SetNull sets the NullableID to null

func (NullableID) String

func (n NullableID) String() string

String returns the ID as string or "NULL"

func (NullableID) StringBytes

func (n NullableID) StringBytes() []byte

StringBytes returns the canonical string representation of the UUID as byte slice: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

func (NullableID) StringOr

func (n NullableID) StringOr(nullStr string) string

StringOr returns the ID as string or the passed nullStr

func (NullableID) StringUpper

func (n NullableID) StringUpper() string

StringUpper returns the upper case version of the canonical string format, or "NULL".

func (*NullableID) UnmarshalBinary

func (n *NullableID) UnmarshalBinary(data []byte) (err error)

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. It will return error if the slice isn't 16 bytes long, but does not check the validity of the UUID.

func (*NullableID) UnmarshalJSON

func (n *NullableID) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler. It supports string and null input. Blank string input does not produce a null ID. It also supports unmarshalling a sql.NullString.

func (*NullableID) UnmarshalText

func (n *NullableID) UnmarshalText(text []byte) (err error)

UnmarshalText implements encoding.TextUnmarshaler. It will unmarshal to a null String if the input is a blank string.

func (NullableID) Valid

func (n NullableID) Valid() bool

Valid returns if Variant and Version of this UUID are supported. A Nil UUID is also valid.

func (NullableID) Validate

func (n NullableID) Validate() error

Validate returns an error if the Variant and Version of this UUID are not supported. A Nil UUID is also valid.

func (NullableID) Value

func (n NullableID) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

func (NullableID) Variant

func (n NullableID) Variant() int

Variant returns an ID layout variant or IDVariantInvalid if unknown.

func (NullableID) Version

func (n NullableID) Version() int

Version returns algorithm version used to generate UUID.

Jump to

Keyboard shortcuts

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