Skip to content

Commit

Permalink
Add encode_hex and decode_hex
Browse files Browse the repository at this point in the history
  • Loading branch information
davidaurelio committed Mar 31, 2015
1 parent 11af4b2 commit 8aad582
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
25 changes: 25 additions & 0 deletions hashids.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,3 +258,28 @@ def decode(self, hashid):
return numbers if hashid == self.encode(*numbers) else ()
except ValueError:
return ()

def encode_hex(self, hex_str):
"""Converts a hexadecimal string (e.g. a MongoDB id) to a hashid.
:param hex_str The hexadecimal string to encodes
>>> Hashids.encode_hex('507f1f77bcf86cd799439011')
'y42LW46J9luq3Xq9XMly'
"""
numbers = (int('1' + hex_str[i:i+12], 16)
for i in range(0, len(hex_str), 12))
try:
return self.encode(*numbers)
except ValueError:
return ''

def decode_hex(self, hashid):
"""Restores a hexadecimal string (e.g. a MongoDB id) from a hashid.
:param hashid The hashid to decode
>>> Hashids.decode_hex('y42LW46J9luq3Xq9XMly')
'507f1f77bcf86cd799439011'
"""
return ''.join(('%x' % x)[1:] for x in self.decode(hashid))
22 changes: 22 additions & 0 deletions test/test_hashids.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,16 @@ def test_negative_call(self):
def test_float_call(self):
assert Hashids().encode(1, 2.5, 3) == ''

def test_encode_hex(self):
assert Hashids().encode_hex('507f1f77bcf86cd799439011') == 'y42LW46J9luq3Xq9XMly'
assert len(Hashids(min_length=1000).encode_hex('507f1f77bcf86cd799439011')) >= 1000
assert Hashids().encode_hex('f000000000000000000000000000000000000000000000000000000000000000000000000000000000000f') == \
'WxMLpERDrmh25Lp4L3xEfM6WovWYO3IjkRMKR2ogCMVzn4zQlqt1WK8jKq7OsEpy2qyw1Vi2p'

def test_illegal_hex(self):
assert Hashids().encode_hex('') == ''
assert Hashids().encode_hex('1234SGT8') == ''

class TestDecoding(object):
def test_empty_string(self):
assert Hashids().decode('') == ()
Expand Down Expand Up @@ -152,3 +162,15 @@ def test_alphabet_with_two_standard_separators(self):
def test_only_one_valid(self):
h = Hashids(min_length=6)
assert h.decode(h.encode(1)[:-1] + '0') == ()

def test_decode_hex(self):
hex_str = '507f1f77bcf86cd799439011'
assert Hashids().decode_hex('y42LW46J9luq3Xq9XMly') == hex_str
h = Hashids(min_length=1000)
assert h.decode_hex(h.encode_hex(hex_str)) == hex_str
assert Hashids().decode_hex('WxMLpERDrmh25Lp4L3xEfM6WovWYO3IjkRMKR2ogCMVzn4zQlqt1WK8jKq7OsEpy2qyw1Vi2p') == \
'f000000000000000000000000000000000000000000000000000000000000000000000000000000000000f'

def test_illegal_decode_hex(self):
assert Hashids().decode_hex('') == ''
assert Hashids().decode_hex('WxMLpERDrmh25Lp4L3xEfM6WovWYO3IjkRMKR2ogCMVlqt1WK8jKq7OsEp1Vi2p') == ''

0 comments on commit 8aad582

Please sign in to comment.