Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 13 additions & 26 deletions hashids.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"errors"
"fmt"
"math"
"regexp"
"strconv"
"strings"
)

Expand Down Expand Up @@ -226,26 +228,15 @@ func (h *HashID) EncodeInt64(numbers []int64) (string, error) {
//
// Each hex nibble is encoded as an integer in range [16, 31].
func (h *HashID) EncodeHex(hex string) (string, error) {
nums := make([]int, len(hex))

for i := 0; i < len(hex); i++ {
b := hex[i]
switch {
case (b >= '0') && (b <= '9'):
b -= '0'
case (b >= 'a') && (b <= 'f'):
b -= 'a' - 'A'
fallthrough
case (b >= 'A') && (b <= 'F'):
b -= ('A' - 0xA)
default:
return "", errors.New("invalid hex digit")
}
// Each int is in range [16, 31]
nums[i] = 0x10 + int(b)
}
reg := regexp.MustCompile(`[\w\W]{1,12}`)
numbers := reg.FindAllString(hex, -1)

return h.Encode(nums)
nums := make([]int64, len(numbers))
for i, number := range numbers {
num, _ := strconv.ParseInt("1"+number, 16, 0)
nums[i] = num
}
return h.EncodeInt64(nums)
}

// DEPRECATED: Use DecodeWithError instead
Expand Down Expand Up @@ -339,13 +330,9 @@ func (h *HashID) DecodeHex(hash string) (string, error) {
return "", err
}

const hex = "0123456789abcdef"
b := make([]byte, len(numbers))
for i, n := range numbers {
if n < 0x10 || n > 0x1f {
return "", errors.New("invalid number")
}
b[i] = hex[n-0x10]
var b string
for _, n := range numbers {
b += strconv.FormatInt(n, 16)[1:]
}
return string(b), nil
}
Expand Down
2 changes: 1 addition & 1 deletion hashids_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func TestEncodeDecodeHex(t *testing.T) {
t.Fatal(err)
}

const expected = "qmTqfesOIqHrsoCYf9UkFZixSKuBT4umuruXuMiDsVsbSrfV"
const expected = "81OP0bv89jEY45DslgBOeD2Qg0kmb7"
if hash != expected {
t.Fatalf("got %q, expected %q", hash, expected)
}
Expand Down