1 #!/usr/bin/env python 2 3 # See: https://answers.atlassian.com/questions/87971/what-is-the-algorithm-used-to-create-the-tiny-links 4 5 from base64 import b64decode, b64encode 6 from struct import pack, unpack 7 import sys 8 9 def tiny_url(s): 10 return b64encode(pack("<I", int(s)).rstrip("\x00")).rstrip("=").replace("+", "_").replace("/", "-") 11 12 def identifier(s): 13 bytes = b64decode(s.replace("-", "/").replace("_", "+") + "=" * (6 - len(s))) 14 return unpack("<I", bytes + "\x00" * (4 - len(bytes)))[0] 15 16 arg = sys.argv[1] 17 reverse = len(sys.argv) > 2 and sys.argv[2] in ("-r", "--reverse") 18 fn = reverse and identifier or tiny_url 19 20 if arg == "-": 21 for line in sys.stdin.readlines(): 22 line = line.strip() 23 if line: 24 print "%s\t%s" % (fn(line), line) 25 else: 26 print fn(arg) 27 28 # vim: tabstop=4 expandtab shiftwidth=4