Skip to content

Commit

Permalink
refactor isofy
Browse files Browse the repository at this point in the history
  • Loading branch information
katsel committed May 18, 2021
1 parent f3323c7 commit 5c6dced
Showing 1 changed file with 7 additions and 15 deletions.
22 changes: 7 additions & 15 deletions src/cnaas_nms/tools/jinja_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ def isofy_ipv4(ip_string, prefix=''):
"""Transform IPv4 address so it can be used as an ISO/NET address.
All four blocks of the IP address are padded with zeros and split up into double octets.
Example: 10.255.255.1 -> 0102.5525.5001.00
With prefix: 10.255.255.1, 47.0023.0000.0001.0000 -> 47.0023.0000.0001.0000.0102.5525.5001.00
Args:
ip_string: a valid IPv4 address
prefix: first part of the ISO address (optional)
Expand All @@ -47,24 +48,15 @@ def isofy_ipv4(ip_string, prefix=''):
if not prefix_valid:
raise ValueError(f"{prefix} cannot be used as ISO prefix, please check formatting")
prefix += '.'

# IP: split and fill with 0s
ip_parts = ip_string.split('.')
padded = [p.zfill(3) for p in ip_parts]
joined = ''.join(padded)

chunksize = 2
ip_octets = [joined[i : i + chunksize] for i in range(0, len(joined), chunksize)]
ip_octets += ['00']

# format: add . after every other octet, starting at the end
ip_octets.reverse()
resultsize = 2 * len(ip_octets) - 1
result = resultsize * ['']
result[1::4] = len(result[1::4]) * '.'
result[0::2] = ip_octets
result.reverse()

iso_address = prefix + ''.join(result)
# IP: split to chunks à 4 chars
chunksize = 4
ip_chunks = [joined[i : i + chunksize] for i in range(0, len(joined), chunksize)]
# combine
iso_address = prefix + '.'.join(ip_chunks) + '.00'
return iso_address


Expand Down

0 comments on commit 5c6dced

Please sign in to comment.