kee

package module
v0.2.5 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2014 License: BSD-3-Clause, MIT Imports: 28 Imported by: 0

README

KEE dot GO

...is a golang single-package library for dealing with resource identifiers and the wacky things they do.

It handles UUIDs/GUIDs, integer identifiers and custom IDs with regular grammar. It also does TOTPs (time-based one time passwords), because that's vaguely related, fits the API and makes the name kind of a pun. Oh, and it generates incoherent nonsense too, if that's your thing.

##Why?

Because fumbling with identifiers and encodings, despite the extensive standard library, is a tedious, somewhat error-prone process that eventually tends to fill a code base with spaghetti. Also, random IDs like "SoppyClownGallopsAimlessly" are a lot more fun than using AUTO_INCREMENT.

##Install Grab the package with:

$ go get github.com/Sam-Izdat/kee

Build Status License MIT GoDoc

##Basic usage

package main

import(
    "fmt"
    "github.com/Sam-Izdat/kee"
)

func main() {
    // Get a random UUID
    id := kee.UUID.New()
    
    // Print it out
    fmt.Println(id)         // => 2d0bbb67-f3f1-4632-9e27-ca3cd7265e22
}

##Making it useful

But wait, there's more...

###The universal and the global

// Get a random UUID
idA := kee.UUID.New()

// Encode it in base 64, URL-safe base 64, ASCII 85, base 32
fmt.Println(idA.B64())      // => LQu7Z/PxRjKeJ8o81yZeIg==
fmt.Println(idA.URL64())    // => LQu7Z_PxRjKeJ8o81yZeIg
fmt.Println(idA.A85())      // => /IT1'oC5:*SgVZCf-XfJ
fmt.Println(idA.B32())      // => FUF3WZ7T6FDDFHRHZI6NOJS6EI======

// Decode another ID from formatted base 32
idB, _ := kee.UUID.Decode("MBW3-UYPY-JFEA-LG32-U6OV-RVGZ-LY")

// Get its raw [16]byte array
fmt.Println(idB.Arr())   
    // => [96 109 186 97 248 73 72 5 155 122 167 157 88 212 217 94]

// Set ID A to the value of ID B
idA = kee.UUID.Set(idB.Arr())

// Check if it's valid
fmt.Println(idB.IsValid())   // => true

// Determine its version and variant
vrs, vrn := idB.Version(), idB.Variant()
fmt.Println("UUID is", vrs, vrn) // => UUID is VERSION_4 RFC4122

// Compare the two
fmt.Println(kee.UUID.Match(idA, idB)) // => true

Available methods for UUID output: Slc, Arr, Hex, A85, B64, URL64, B32, URL32 and URN.

The Decode method of the UUID handler accepts any valid string output listed above.

See documentation or source for UUIDs other than Version 4.

###The less cosmopolitan identifiers

// Make a fixed precision integer identifier
idfa := kee.FPIID.FromInt(555555555555555)

// Variable parameters must be typed uint64
var myInt int = 12345
idfb := kee.FPIID.FromInt(uint64(myInt))

fmt.Println(idfa, "&", idfb)    // => 47iKW0b5AQA & OTA
fmt.Println(idfa.URL32())       // => 4O4I-UW2G-7EAQ-A

// Decode from base 64
idfc, _ := kee.FPIID.Decode("OTA")
fmt.Println(idfc.Int()) // => 12345

// Make an arbitrary-precision integer identifier
idaa := kee.APIID.FromString("654654654654654654654654")
idab := kee.APIID.FromInt(512)
fmt.Println(idaa, "&", idab) // => 8MJbCS5foMSAeC & 9Q

// Decode from base 58
idac, _ := kee.APIID.Decode("9Q")
fmt.Println(idac.BigInt()) // => 512

Available methods for FPIID output are: Slc, Arr, Int, B64, URL64, B32, and URL32.

Available methods for APIID output are: Slc, BigInt, and B58.

The Decode method of the FPIID/APIID handlers accepts any valid string output listed above.

###SplendidToucanVanishDarkly

// ScrawlyFittersFlounderWhither
wut, _ := kee.JUMBLE.New(2,2,2,2)

fmt.Println(wut)
// => FlabbyAgnatesUnhorsedLeftwards

fmt.Println(wut.SampleSpace())
// => 755632777339440

wut, _ = kee.JUMBLE.New(1,4,2,0)
fmt.Println(wut, wut.SampleSpace())
// => GorgedLethalityComplied 72298351944

FatiguedPhalangeTriggingBackward? InboundClaptrapPreludesNudely.

###Multi-factor authentication

// Generate a secret
newSecret := kee.TOTP.New()

// Get its [32]byte slice for later use
data := newSecret.Slc()   // only available after New() -- check for nil

// Set a previous secret
secret := kee.TOTP.Set(data)

// Print it in formatted base 32
fmt.Println(secret)       // => KRNX-EGXV-JZVR-GN6P-AF3D-LNO7-UGI7-YMX6

// ...or a URI to make a QR code
uri := secret.URI("Acct Name", "Issuer")
fmt.Println(uri) 
    // => otpauth://totp/Acct+Name?secret=[blabla]&issuer=Issuer

// Generate one-time passowrd(s)
expected, _ := secret.MakePassword()

// Compare it with the password received
received := uint32(123456)
openSafe := kee.TOTP.MatchPasswords(expected, received)

This is generally intended for mobile devices and works with the Google Authenticator application.

##Advanced usage

An ID instance comes from the handler of its respective type:

  • UUID for Universally/Globally Unique Identifiers
  • FPIID for Fixed Precision Integer Identifiers
  • APIID for Arbitrary Precision Integer Identifiers
  • TOTP for Time-based One-time Passwords
  • JUMBLE for Gibberish

These handlers share few common methods where appropriate -- at least in purpose, by convention:

  • New() creates a new (meaning original) locally, globally, universally or multiversally unique identifier from scratch. Invoking this method may generate random data, increment a counter or query a database to return a unique identifier; it may take parameters, such as data for a hash function

  • Set() takes a byte slice or a byte array representing an existing ID and manually assigns the ID instance its definitive value

  • Decode() derives the instance's value from some formatted or unformatted encoding (like hex, base 32, ASCII 35, etc) representing an existing ID

You can extend functionality by writing your own handlers and two built-in methods are reserved just for such occasions:

  • Parse() maps out data from the canonical string representation of some ID

  • Compose() takes a map of that data and reassembles the ID according to its defined structure

While there's not much information to be gleaned from essentially random bits and incrementing integers, many identifiers can have a bit more to say. Let's write a handler for ISBNs.

package main

import (
    "fmt"
    "strconv"
    "github.com/Sam-Izdat/kee"
)

// Define the capture groups with a regular expression pattern
var isbn13pat string = `(?P<label>ISBN|ISBN-13)+[ ]` + 
    `(?P<prefix>`       + `[0-9]*)+[- ]` + 
    `(?P<group>`        + `[0-9]*)+[- ]` +
    `(?P<publisher>`    + `[0-9]*)+[- ]` +
    `(?P<title>`        + `[0-9]*)+[- ]` + 
    `(?P<checksum>`     + `[0-9]*)`

// Define a standard-library template for its canonical format
var isbn13tmpl string = `ISBN-13 {{.prefix}}-{{.group}}-` + 
    `{{.publisher}}-{{.title}}-{{.checksum}}`

// Grab an ID handler
var ISBN = kee.NewHandler(isbn13pat, isbn13tmpl)

// The ID instances should embed the generic ID struct
type isbn struct {
    kee.GenericID
}

// Write any methods you need for your ID instances
// e.g. compute checksum and compare it to check digit
func (p isbn) Check() bool {
    var m map[string]string = p.Map()
    var digits string = (
        m["prefix"] + m["group"] + 
        m["publisher"] + m["title"])
    var sum, weight, tmp int
    var checkdigit, _ = strconv.Atoi(m["checksum"])
    if checkdigit == 0 { checkdigit = 10}
    for k, v := range digits {
        if (k + 1) % 2 == 0 {
            weight = 3
        } else { weight = 1 }
        tmp, _ = strconv.Atoi(string(v))
        sum += tmp * weight
    }
    return 10 - (sum % 10) == checkdigit
}

func main() {
    // Get generic ID instance
    ida, _ := ISBN.Parse("ISBN 978-0-306-40615-7") 
    idb := isbn{ida} // Embed generic ID in isbn instance

    // Test it out
    fmt.Println(ISBN.Compose(idb.Map())) 
        // => ISBN-13 978-0-306-40615-7 <nil>

    // Verify check digit
    fmt.Println(idb.Check()) // => true
}

What's provided is really just scaffolding for anyone wishing to follow the conventions above for convenience, consistency and improved code readability. More functionality may be added on later.

Potential gotchas

  • Encoded strings are cached to avoid re-encoding the same string every time it's requested. If you need to change the options after creating an ID (e.g. to remove padding or change formatting), turn off the appopriate Cache option and consider managing your own variables if performance is a factor.
    id := kee.UUID.New()
    fmt.Println( id.URL32() ) // => Y46J-ZTZ4-3NFO-JBM5-4MLR-BLJR-3M
    kee.UUID.Options.HyphURL32 = false
    fmt.Println( id.URL32() ) // => Y46J-ZTZ4-3NFO-JBM5-4MLR-BLJR-3M
    kee.UUID.Options.Cache = false
    fmt.Println( id.URL32() ) // => Y46JZTZ43NFOJBM54MLRBLJR3M
  • Version 2 (DCE Security) UUIDs have been axed on account of being unnatural, easy to misuse and generally ridiculous.
    if _, err := kee.UUID.NewV2(); err != nil {
        fmt.Println(err) // => no
    }
  • A lot of UUID/GUID implementations ignore the RFC spec, just fill 16 bytes with random porridge and call it a day. This porridge will generally be rejected unless the right nibbles just happen to identify it as something it probably isn't. If you absolutely need to accept this porridge, set the AcceptInvalid option to true.
    if _, err := kee.UUID.Decode("12341324-1234-0000-0000-123412341234"); err != nil {
        fmt.Println(err) // => Invalid UUID
    }
  • Arbitrary-precision integers are really arbitrary in size just as their encoded versions are in length. If you plan on counting past eighteen quintillion or dividing by zero please mind the constraints and fasten appropriate protective head gear.
    id := kee.APIID.New("18446744073709551615") 
    fmt.Println(id.BigInt().Uint64())  // => 18446744073709551615
    id = kee.APIID.New("18446744073709551616") // uint64 will overflow
    fmt.Println(id.BigInt().Uint64())  // => 0
    id = kee.APIID.New("28446744073709551616") 
    fmt.Println(id.BigInt().Uint64())  // => 10000000000000000000
    fmt.Println(id.BigInt())           // => 28446744073709551616
  • Check that the server time is exactly correct when using time-based passwords.
  • Some JUMBLE words are quite long. If storing phrases in a database, allow for at least 100 characters. Unless words are omitted, the sample space is usually very large but still well below a UUID; checking for collisions is a good idea.
  • Please, dear god, don't try to parse email addresses with regular expressions. You have been warned.

#What still needs doin'

  • Complete unit tests
  • Some base set of built-in regular expressions for parsing common identifiers

#Attributions Code or content anonymously pinched from:

#License

MIT with some BSD-licensed snippets

Documentation

Overview

Package kee simplifies generating, parsing, composing, encoding and decoding resource identifiers

Index

Constants

This section is empty.

Variables

View Source
var (
	// UUID handler for creating Universally Unique Identifiers
	UUID UUIDCtrl

	// FPIID handler for creating Fixed Precision Integer Identifiers
	FPIID FPIIDCtrl

	// APIID handler for creating Arbitrary Precision Integer Identifiers
	APIID APIIDCtrl

	// TOTP handler for One-time Time Based Passwords
	TOTP TOTPCtrl

	// JUMBLE handler for word-jumble identifiers
	JUMBLE JUMCtrl
)
View Source
var APIIDOptions = apiidConfig{
	Cache: true,
}

APIIDOptions defines the configuration used by the `kee.APIID` handler. Options can also be changed through `kee.APIID.Options`.

View Source
var FPIIDOptions = FPIIDConfig{
	Cache:     true,
	ShortStr:  true,
	PadB64:    true,
	PadB32:    true,
	HyphURL32: true,
}

FPIIDOptions defines the configuration used by the `kee.FPIID` handler. Options can also be changed through `kee.FPIID.Options`.

View Source
var TOTPOptions = TOTPConfig{
	LookAhead:  1,
	LookBehind: 1,
	B32Blocks:  8,
	HyphB32:    true,
}

TOTPOptions defines the configuration used by the `kee.TOTP` handler. Options can also be changed through `kee.TOTP.Options`.

View Source
var UUIDOptions = UUIDConfig{
	Cache:        true,
	AllowInvalid: false,
	MinVer:       1,
	MaxVer:       5,
	PadB64:       true,
	PadB32:       true,
	WrapA85:      false,
	HyphURL32:    true,
}

UUIDOptions defines the configuration used by the `kee.UUID` handler. Options can also be changed through `kee.UUID.Options`.

Functions

func ClockSequence

func ClockSequence() int

ClockSequence returns the current clock sequence, generating one if not already set. The clock sequence is only used for Version 1 UUIDs.

The UUID package does not use global static storage for the clock sequence or the last time a UUID was generated. Unless SetClockSequence a new random clock sequence is generated the first time a clock sequence is requested by ClockSequence, GetTime, or NewUUID. (section 4.2.1.1) sequence is generated for

func SetClockSequence

func SetClockSequence(seq int)

SetClockSequence sets the clock sequence to the lower 14 bits of seq. Setting to -1 causes a new sequence to be generated.

Types

type APIIDCtrl added in v0.2.0

type APIIDCtrl struct {
	Options *apiidConfig
}

APIIDCtrl is a struct for the APIID handler. Unless another handler with different options is needed simply use instance `kee.APIID`.

func (APIIDCtrl) Decode added in v0.2.0

func (c APIIDCtrl) Decode(s string) (KAPIID, error)

Decode takes base 58 encoded string of APIID and returns KAPIID instance

func (APIIDCtrl) FromBigInt added in v0.2.0

func (c APIIDCtrl) FromBigInt(api *big.Int) KAPIID

FromBigInt takes math/big Int and return KAPIID instance

func (APIIDCtrl) FromInt added in v0.2.0

func (c APIIDCtrl) FromInt(fpi uint64) KAPIID

FromInt takes 64-bit integer and return KAPIID instance

func (APIIDCtrl) FromString added in v0.2.0

func (c APIIDCtrl) FromString(s string) KAPIID

FromString takes string representation of arbitrary precision integer and return KAPIID instance

func (APIIDCtrl) Set added in v0.2.0

func (c APIIDCtrl) Set(slc []byte) KAPIID

Set takes an arbitrary-length byte slice and returns KAPIID instance

type FPIIDConfig added in v0.2.5

type FPIIDConfig struct {
	Cache, ShortStr           bool
	PadB64, PadB32, HyphURL32 bool
}

FPIIDConfig is the struct for FPIIDOptions. It should only be used if another handler with a different set of options is being created.

type FPIIDCtrl added in v0.2.0

type FPIIDCtrl struct {
	Options *FPIIDConfig
}

FPIIDCtrl is a struct for the APIID handler. Unless another handler with different options is needed simply use instance `kee.FPIID`.

func (FPIIDCtrl) Decode added in v0.2.0

func (c FPIIDCtrl) Decode(s string) (KFPIID, error)

Decode takes encoded string of FPIID and returns KFPIID instance

func (FPIIDCtrl) FromInt added in v0.2.0

func (c FPIIDCtrl) FromInt(id uint64) KFPIID

FromInt takes a [8]byte array and returns a KFPIID instance

func (FPIIDCtrl) Set added in v0.2.0

func (c FPIIDCtrl) Set(arr [8]byte) KFPIID

Set takes an [8]byte array and returns a KFPIID instance

type GenericID

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

GenericID type is for custom identifiers

func (GenericID) Map

func (id GenericID) Map() map[string]string

Map returns a map of ID values specfied by handler's regex

func (GenericID) String

func (id GenericID) String() string

String returns canonical string representation of the ID

type Handler added in v0.2.5

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

Handler is a handler for custom IDs. Use NewHandler to instantiate.

func NewHandler

func NewHandler(repat string, tmpl string) Handler

NewHandler returns a custom ID handler with provided pattern and template

func (Handler) Compose added in v0.2.5

func (p Handler) Compose(m map[string]string) (GenericID, error)

Composes m using supplied template and returns GenericID instance

func (Handler) Parse added in v0.2.5

func (p Handler) Parse(s string) (GenericID, error)

Parses s using supplied regexp and returns GenericID instance

type JUMCtrl added in v0.2.0

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

JUMCtrl is a struct for the JUMBLE handler. Unless another handler is needed simply use instance `kee.JUMBLE`.

func (*JUMCtrl) New added in v0.2.0

func (j *JUMCtrl) New(sylAdj, sylNoun, sylVerb, sylAdv int) (KJUMBLE, error)

New generates a random phrase and returns KJUMBLE instance; takes number of syllables for adjective, noun, verb, adverb respectively. Pass 0 as syllable count to skip word.

type KAPIID added in v0.2.0

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

KAPIID type represents an arbitrary precision integer identifier. It is exported only for reference and should be instantiated through its handler's methods.

func (KAPIID) B58 added in v0.2.0

func (id KAPIID) B58() (res string)

B58 returns base 58 encoded string representation of APIID

func (KAPIID) BigInt added in v0.2.0

func (id KAPIID) BigInt() (res *big.Int)

BigInt returns APIID as a math/big Int

func (KAPIID) Slc added in v0.2.0

func (id KAPIID) Slc() []byte

Slc returns APIID as slice

func (KAPIID) String added in v0.2.0

func (id KAPIID) String() string

String is alias for B58()

type KFPIID added in v0.2.0

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

KFPIID type represents a fixed precision integer identifier. It is exported only for reference and should be instantiated through its handler's methods.

func (KFPIID) Arr added in v0.2.0

func (id KFPIID) Arr() (res [8]byte)

Arr returns FPIID as array

func (*KFPIID) B32 added in v0.2.0

func (id *KFPIID) B32() string

B32 returns base 32 encoded string representation of FPIID

func (*KFPIID) B64 added in v0.2.0

func (id *KFPIID) B64() string

B64 returns base 64 encoded string representation of FPIID

func (KFPIID) Int added in v0.2.0

func (id KFPIID) Int() (res uint64)

Int returns FPIID as unsigned 64 bit integer

func (KFPIID) Slc added in v0.2.0

func (id KFPIID) Slc() []byte

Slc returns FPIID as slice

func (KFPIID) String added in v0.2.0

func (id KFPIID) String() string

String is alias for URL64

func (*KFPIID) URL32 added in v0.2.0

func (id *KFPIID) URL32() string

URL32 returns formatted, URL-safe base 32 string representation of FPIID

func (*KFPIID) URL64 added in v0.2.0

func (id *KFPIID) URL64() string

URL64 returns URL-safe base 64 string representation FPIID

type KJUMBLE added in v0.2.0

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

KJUMBLE type represents a word jumble phrase. It is exported only for reference and should be instantiated through its handler's methods.

func (KJUMBLE) SampleSpace added in v0.2.0

func (m KJUMBLE) SampleSpace() uint64

SampleSpace returns the sample space (number of variations) possible for this phrase

func (KJUMBLE) String added in v0.2.0

func (m KJUMBLE) String() string

String prints the phrase in camel case

type KTOTP added in v0.2.0

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

KTOTP type represents a secret capable of producing time-based one time passwords. (RFC 6238) It is exported only for reference and should be instantiated through its handler's methods.

func (*KTOTP) B32 added in v0.2.0

func (id *KTOTP) B32() string

B32 returns base 32 encoded string representation of secret

func (*KTOTP) MakePassword added in v0.2.0

func (id *KTOTP) MakePassword() ([]uint32, error)

MakePassword returns a slice of 6-digit time based passwords

func (*KTOTP) Slc added in v0.2.0

func (id *KTOTP) Slc() []byte

Slc returns secret as slice. This method is only meant to be used immediately after generating or loading a 32-byte secret to store it somewhere permanently.

func (*KTOTP) String added in v0.2.0

func (id *KTOTP) String() string

String is alias for B32()

func (*KTOTP) URI added in v0.2.0

func (id *KTOTP) URI(acct, issuer string) string

URI returns Uniform Resource Identifier with secret for QR code generation

type KUUID added in v0.2.0

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

KUUID type represents a Universally unique identifier. (RFC 4122) It is exported only for reference and should be instantiated through its handler's methods.

func (*KUUID) A85 added in v0.2.0

func (id *KUUID) A85() string

A85 returns ASCII 85 encoded string representation of UUID

func (KUUID) Arr added in v0.2.0

func (id KUUID) Arr() (res [16]byte)

Arr returns UUID as array

func (*KUUID) B32 added in v0.2.0

func (id *KUUID) B32() string

B32 returns base 32 encoded string representation of UUID

func (*KUUID) B64 added in v0.2.0

func (id *KUUID) B64() string

B64 returns base 64 encoded string representation of UUID

func (KUUID) ClockSequence added in v0.2.0

func (id KUUID) ClockSequence() (int, bool)

ClockSequence returns the clock sequence encoded in UUID. It returns false if UUID is not valid. The clock sequence is only well defined for version 1 and 2 UUIDs.

func (*KUUID) Hex added in v0.2.0

func (id *KUUID) Hex() string

Hex returns canonical hex string representation of UUID, as in RFC 4122

func (KUUID) IsValid added in v0.2.0

func (id KUUID) IsValid() (valid bool)

IsValid returns true if the the UUID is valid according to settings, false if not

func (KUUID) NodeID added in v0.2.0

func (id KUUID) NodeID() []byte

NodeID returns the 6 byte node id encoded in UUID. It returns nil if UUID is not valid. The NodeID is only well defined for version 1 and 2 UUIDs.

func (KUUID) Slc added in v0.2.0

func (id KUUID) Slc() []byte

Slc returns UUID as slice

func (KUUID) String added in v0.2.0

func (id KUUID) String() string

String is alias for Hex

func (KUUID) Time added in v0.2.0

func (id KUUID) Time() (Time, bool)

Time returns the time in 100s of nanoseconds since 15 Oct 1582 encoded in UUID. It returns false if UUID is not valid. The time is only well defined for version 1 and 2 UUIDs.

func (*KUUID) URL32 added in v0.2.0

func (id *KUUID) URL32() string

URL32 returns formatted, URL-safe base 32 representation of UUID

func (*KUUID) URL64 added in v0.2.0

func (id *KUUID) URL64() string

URL64 returns URL-safe base 64 representation UUID

func (*KUUID) URN added in v0.2.0

func (id *KUUID) URN() string

URN returns hex URN of UUID, as in RFC 2141

func (KUUID) Variant added in v0.2.0

func (id KUUID) Variant() uuidVariant

Variant returns the variant encoded in uuid. It returns Invalid if uuid is invalid.

func (KUUID) Version added in v0.2.0

func (id KUUID) Version() uuidVersion

Version returns the verison of uuid. It returns 0 if uuid is not valid.

type TOTPConfig added in v0.2.5

type TOTPConfig struct {
	LookAhead, LookBehind, B32Blocks int
	HyphB32                          bool
}

TOTPConfig is the struct for TOTPOptions. It should only be used if another handler with a different set of options is being created.

type TOTPCtrl added in v0.2.0

type TOTPCtrl struct {
	Options *TOTPConfig
}

TOTPCtrl is a struct for the TOTP handler. Unless another handler with different options is needed simply use instance `kee.TOTP`.

func (TOTPCtrl) Decode added in v0.2.0

func (c TOTPCtrl) Decode(s string) (KTOTP, error)

Decode takes base 32 encoded string of secret and returns KTOTP instance

func (TOTPCtrl) MatchPasswords added in v0.2.0

func (c TOTPCtrl) MatchPasswords(exp []uint32, rec uint32) bool

MatchPasswords compares expected and received secrets, return true if they match, false if not

func (TOTPCtrl) New added in v0.2.0

func (c TOTPCtrl) New() KTOTP

New generates a new secret and returns KTOTP instance

func (TOTPCtrl) Set added in v0.2.0

func (c TOTPCtrl) Set(bytes []byte) KTOTP

Set loads an existing secret and returns KTOTP instance

type Time

type Time int64

A Time represents a time as the number of 100's of nanoseconds since 15 Oct 1582.

func GetTime

func GetTime() (Time, error)

GetTime returns the current Time (100s of nanoseconds since 15 Oct 1582) and adjusts the clock sequence as needed. An error is returned if the current time cannot be determined.

func (Time) UnixTime

func (t Time) UnixTime() (sec, nsec int64)

UnixTime converts t the number of seconds and nanoseconds using the Unix epoch of 1 Jan 1970.

type UUIDConfig added in v0.2.5

type UUIDConfig struct {
	Cache, AllowInvalid                bool
	MinVer, MaxVer                     uint8
	PadB64, PadB32, WrapA85, HyphURL32 bool
}

UUIDConfig is the struct for UUIDOptions. It should only be used if another handler with a different set of options is being created.

type UUIDCtrl added in v0.2.0

type UUIDCtrl struct {
	Options *UUIDConfig
	NS      map[string]string // Namespaces
}

UUIDCtrl is a struct for the UUID handler. Unless another handler with different options is needed simply use instance `kee.UUID`.

func (UUIDCtrl) Decode added in v0.2.0

func (c UUIDCtrl) Decode(s string) (KUUID, error)

Decode takes encoded string of UUID and returns KUUID instance

func (UUIDCtrl) Match added in v0.2.0

func (_ UUIDCtrl) Match(ida, idb KUUID) bool

Match takes two KUUID instances; returns `true` if they are identical or false if not

func (UUIDCtrl) New added in v0.2.0

func (c UUIDCtrl) New() KUUID

New is alias for NewV4; returns random Version 4 UUID and as KUUID instance

func (UUIDCtrl) NewV1 added in v0.2.0

func (c UUIDCtrl) NewV1() (KUUID, error)

NewV1 returns a Version 1 UUID based on the current NodeID and clock sequence, and the current time. If the NodeID has not been set by SetNodeID or SetNodeInterface then it will be set automatically. If the NodeID cannot be set NewUUID returns nil. If clock sequence has not been set by SetClockSequence then it will be set automatically. If GetTime fails to return the current NewUUID returns nil.

func (UUIDCtrl) NewV2 added in v0.2.0

func (c UUIDCtrl) NewV2() (KUUID, error)

May need some refactoring

func (UUIDCtrl) NewV3 added in v0.2.0

func (c UUIDCtrl) NewV3(id KUUID, data []byte) (KUUID, error)

NewMD5 returns a new MD5 (Version 3) UUID based on the supplied name space and data. Furst

func (UUIDCtrl) NewV4 added in v0.2.0

func (c UUIDCtrl) NewV4() (KUUID, error)

NewV4 returns a Random (Version 4) UUID or panics.

The strength of the UUIDs is based on the strength of the crypto/rand package.

A note about uniqueness derived from from the UUID Wikipedia entry:

Randomly generated UUIDs have 122 random bits.  One's annual risk of being
hit by a meteorite is estimated to be one chance in 17 billion, that
means the probability is about 0.00000000006 (6 × 10−11),
equivalent to the odds of creating a few tens of trillions of UUIDs in a
year and having one duplicate.

func (UUIDCtrl) NewV5 added in v0.2.0

func (c UUIDCtrl) NewV5(id KUUID, data []byte) (KUUID, error)

NewV5 returns a new SHA1 (Version 5) UUID based on the supplied name space and data.

func (UUIDCtrl) NodeID added in v0.2.0

func (c UUIDCtrl) NodeID() []byte

NodeID returns a slice of a copy of the current Node ID, setting the Node ID if not already set.

func (UUIDCtrl) NodeInterface added in v0.2.0

func (_ UUIDCtrl) NodeInterface() string

NodeInterface returns the name of the interface from which the NodeID was derived. The interface "user" is returned if the NodeID was set by SetNodeID.

func (UUIDCtrl) Set added in v0.2.0

func (c UUIDCtrl) Set(arr [16]byte) KUUID

Set takes a [16]byte array and returns KUUID instance

func (UUIDCtrl) SetNodeID added in v0.2.0

func (c UUIDCtrl) SetNodeID(id []byte) bool

SetNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes of id are used. If id is less than 6 bytes then false is returned and the Node ID is not set.

func (UUIDCtrl) SetNodeInterface added in v0.2.0

func (c UUIDCtrl) SetNodeInterface(name string) bool

SetNodeInterface selects the hardware address to be used for Version 1 UUIDs. If name is "" then the first usable interface found will be used or a random Node ID will be generated. If a named interface cannot be found then false is returned.

SetNodeInterface never fails when name is "".

Jump to

Keyboard shortcuts

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