Skip to content

Instantly share code, notes, and snippets.

@Xjs
Created May 24, 2009 16:27
Show Gist options
  • Save Xjs/117177 to your computer and use it in GitHub Desktop.
Save Xjs/117177 to your computer and use it in GitHub Desktop.
# Copyright (c) 2009 Jannis Andrija Schnitzer
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from base64 import b64encode as base64_encode, b64decode as base64_decode
def n_at_once(string, n):
"""Return an iterator over substrings of the given string
with length n"""
while string:
prefix, string = string[:n], string[n:]
yield prefix
def shorten(address):
address = address.lower() # ensure we yield the same string on case differences
splices = address.split(':')
result = []
for splice in splices:
if not splice:
result.append('_')
else:
splice = splice.rjust(4, '0')
for hex_number in n_at_once(splice, 2):
hex_number = int(hex_number, 16)
result.append(chr(hex_number))
return base64_encode(''.join(result))
def expand(address):
address = base64_decode(address)
pieces = []
for character in address:
if character == '_':
pieces.extend(['', ''])
else:
pieces.append(hex(ord(character))[2:].rjust(2, '0'))
print pieces
return ':'.join(''.join(splices).lstrip('0') for splices in n_at_once(pieces, 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment