diff --git a/README.md b/README.md index 92a7238..47d5c62 100644 --- a/README.md +++ b/README.md @@ -36,11 +36,42 @@ is very performant in a distributed environment. Some estimates for this perform ### Installation -TBD. +Installation is as simple as running: +```bash +go get github.com/MrM21632/snowball +``` + +And importing the module into your code is also simple: +```go +import ( + "github.com/MrM21632/snowball" +) +``` ### Usage -TBD. +First, ensure `SNOWBALL_EPOCH_MS` and `SNOWBALL_NODE_ID` are defined in the system environment variables. From there, +utilizing the module is very straightforward. Import the package normally, initialize a new server node using `InitNode()`, +then call `GenerateID()` to create and retrieve a new Snowball ID. +```go +package main + +import ( + "fmt" + "github.com/MrM21632/snowball" +) + +func main() { + node, err := snowball.InitNode() + if err != nil { + fmt.Println(err) + return + } + + id := node.GenerateID() + // ... do what you need with the ID afterwards. +} +``` ### Testing diff --git a/encode.go b/encode.go index feac80a..5ca8af9 100644 --- a/encode.go +++ b/encode.go @@ -5,9 +5,13 @@ import ( "encoding/base64" "encoding/binary" "errors" + "math" "strconv" + "strings" ) +const base62Digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + // Formats the Snowball ID into a binary string. func (id SnowballID) ToBinary() string { return strconv.FormatUint(uint64(id), 2) @@ -64,3 +68,31 @@ func FromBase64(sid string) (SnowballID, error) { return SnowballID(binary.NativeEndian.Uint64(bytes)), nil } + +// Formats the Snowball ID into a base62 encoded string. +func (id SnowballID) ToBase62() string { + result := "" + for id > 0 { + remainder := id % 62 + result = string(base62Digits[remainder]) + result + id /= 62 + } + + return result +} + +// Converts a base62 string into a Snowball ID. +func FromBase62(sid string) (SnowballID, error) { + var result uint64 + for index, char := range sid { + pow := len(sid) - (index + 1) + pos := strings.IndexRune(base62Digits, char) + if pos == -1 { + return 0, errors.New("decode failed: invalid base62 string") + } + + result += uint64(pos) * uint64(math.Pow(62, float64(pow))) + } + + return SnowballID(result), nil +} diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..e69de29