Skip to content

Commit 16ad349

Browse files
committed
EncodeHex: much faster implementation
1 parent d7bc721 commit 16ad349

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

hashids.go

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import (
1010
"errors"
1111
"fmt"
1212
"math"
13-
"strconv"
1413
"strings"
1514
)
1615

@@ -225,15 +224,23 @@ func (h *HashID) EncodeInt64(numbers []int64) (string, error) {
225224
// A hexadecimal string should not contain the 0x prefix.
226225
// Use DecodeHex using the same Alphabet and Salt to get back the hexadecimal string.
227226
func (h *HashID) EncodeHex(hex string) (string, error) {
228-
chars := []rune(hex)
229-
nums := []int{}
230-
231-
for _, s := range chars {
232-
n, err := strconv.ParseInt(fmt.Sprintf("1%s", string(s)), 16, 64)
233-
if err != nil {
234-
return "", err
227+
nums := make([]int, len(hex))
228+
229+
for i := 0; i < len(hex); i++ {
230+
b := hex[i]
231+
switch {
232+
case (b >= '0') && (b <= '9'):
233+
b -= '0'
234+
case (b >= 'a') && (b <= 'f'):
235+
b -= 'a' - 'A'
236+
fallthrough
237+
case (b >= 'A') && (b <= 'F'):
238+
b -= ('A' - 0xA)
239+
default:
240+
return "", errors.New("invalid hex digit")
235241
}
236-
nums = append(nums, int(n))
242+
// Each int is in range [16, 31]
243+
nums[i] = 0x10 + int(b)
237244
}
238245

239246
return h.Encode(nums)

0 commit comments

Comments
 (0)