Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
4 changes: 2 additions & 2 deletions hashids_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func TestEncodeDecodeEpoch(t *testing.T) {

func TestEncodeDecodeHex(t *testing.T) {
hdata := NewData()
hdata.MinLength = 30
hdata.MinLength = 8
Copy link

@ghost ghost May 21, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do you change the MinLength? What is the result if you leave it at 30? If you change the implementation, leave the unit test unchanged.

Copy link
Author

@mashmooli mashmooli May 21, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for replying. i had turn backed it to 'MinLength = 30'
and you can check it with js example in: https://codepen.io/anon/pen/arVLpG

hdata.Salt = "this is my salt"

hid, _ := NewWithData(hdata)
Expand All @@ -84,7 +84,7 @@ func TestEncodeDecodeHex(t *testing.T) {
t.Fatal(err)
}

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