Skip to content

Commit

Permalink
Change base62 input type to uint64.
Browse files Browse the repository at this point in the history
  • Loading branch information
ejholmes committed Jun 17, 2016
1 parent 3212859 commit a70ba39
Show file tree
Hide file tree
Showing 3 changed files with 5 additions and 55 deletions.
28 changes: 2 additions & 26 deletions pkg/base62/base62.go
Original file line number Diff line number Diff line change
@@ -1,23 +1,18 @@
// Package base62 implements conversion to and from base62. Useful for url shorteners.
package base62

import (
"bytes"
"math"
)

// characters used for conversion
const alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

// converts number to base62
func Encode(number int) string {
func Encode(number uint64) string {
if number == 0 {
return string(alphabet[0])
}

chars := make([]byte, 0)

length := len(alphabet)
length := uint64(len(alphabet))

for number > 0 {
result := number / length
Expand All @@ -32,22 +27,3 @@ func Encode(number int) string {

return string(chars)
}

// converts base62 token to int
func Decode(token string) int {
number := 0
idx := 0.0
chars := []byte(alphabet)

charsLength := float64(len(chars))
tokenLength := float64(len(token))

for _, c := range []byte(token) {
power := tokenLength - (idx + 1)
index := bytes.IndexByte(chars, c)
number += index * int(math.Pow(charsLength, power))
idx++
}

return number
}
30 changes: 2 additions & 28 deletions pkg/base62/base62_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@ import "testing"

func Test_Encode(t *testing.T) {
tests := []struct {
Input int
Input uint64
Expected string
}{
{1024, "gw"},
{512347, "29hF"},
{5369806, "mwVM"},
{2147483647, "2lkCB1"},
{0xFFFFFFFFFFFFFFFF, "lYGhA16ahyf"}, // Max uint64
}

for i, test := range tests {
Expand All @@ -21,30 +22,3 @@ func Test_Encode(t *testing.T) {
}
}
}

func Test_Decode(t *testing.T) {
tests := []struct {
Input string
Expected int
}{
{"gw", 1024},
{"29hF", 512347},
{"10", 62},

// Maximum sizes
{"Z", 61},
{"ZZ", 3843},
{"ZZZ", 238327},
{"ZZZZ", 14776335},
{"ZZZZZ", 916132831},
{"ZZZZZZ", 56800235583}, // We'll probably never get here
}

for i, test := range tests {
d := Decode(test.Input)

if d != test.Expected {
t.Errorf("%v: Got %v, want %v", i, d, test.Expected)
}
}
}
2 changes: 1 addition & 1 deletion server/cloudformation/ecs.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,5 +198,5 @@ func postfix(p *ECSServiceProperties) (string, error) {
if err != nil {
return "", err
}
return base62.Encode(int(h)), nil
return base62.Encode(h), nil
}

0 comments on commit a70ba39

Please sign in to comment.