Skip to content

Commit

Permalink
Encodings for base62, more details in README
Browse files Browse the repository at this point in the history
  • Loading branch information
MrM21632 committed Feb 24, 2024
1 parent 3466ada commit 9d56518
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 2 deletions.
35 changes: 33 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
32 changes: 32 additions & 0 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
}
Empty file added go.sum
Empty file.

0 comments on commit 9d56518

Please sign in to comment.