Matthew Stobbs
d00ac81a29
Not tested, only written code. Tests will come next to verify that it works
59 lines
1.6 KiB
Go
59 lines
1.6 KiB
Go
package tind
|
|
|
|
// TinD: Because a UUID is too big for a lot of people
|
|
// a TinD is a defaults to a 4 byte ID made up of ONLY Alphabetical characters.
|
|
// To ensure more randomness, lower case and upper case letters are used
|
|
// providing up to 52 differenct characters for use in each single position.
|
|
// Arbitrary TinD sizes can also be used, by calling
|
|
// `id := NewTinDOfLength(<number of bytes>)`
|
|
//
|
|
// TinD is at it's core a byte slice. It's default alphabet can be replaced with
|
|
// whatever unicode characters you want, as the alphabet it uses is just a slice
|
|
// of runes
|
|
import (
|
|
"crypto/rand"
|
|
"errors"
|
|
"log"
|
|
)
|
|
|
|
// defaults are just a call to NewConfig()
|
|
var defaults = NewTinDConfig()
|
|
|
|
// TinD represents a very simple `size` byte unique ID that is generated
|
|
// at random. TinD stands for Tiny iDentifier, and is pronouced "tind"
|
|
// Each byte can be the value 0 -> len(alphabet) that is used, to ensure
|
|
// values can be encoded and decoded reliably. The longer the alphabet
|
|
// used, the more randomness can be done.
|
|
type TinD struct{
|
|
bytes []byte
|
|
str string
|
|
config *Config
|
|
}
|
|
|
|
// Gen generates a new TinD id using default values
|
|
func Gen() TinD {
|
|
return defaults.Gen()
|
|
}
|
|
|
|
// String returns the Human Readable form of the TinD
|
|
func (t TinD) String() string {
|
|
if len(t.str) == t.config.size {
|
|
return t.str
|
|
}
|
|
t.str = makeString(t.bytes, t.config.size, t.config.runset)
|
|
return t.str
|
|
}
|
|
|
|
// Bytes returns the raw bytes of the TinD
|
|
func (t TinD) Bytes() []byte {
|
|
return t.bytes
|
|
}
|
|
|
|
func makeString(bytes []byte, size int, runeset []rune) string {
|
|
r := make([]rune, size)
|
|
for i := 0; i < size; i++ {
|
|
r[i] = runeset[bytes[i]]
|
|
}
|
|
return string(r)
|
|
}
|