Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/netaddr/ip/rfc1924.py: 36%

28 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-07 06:45 +0000

1#----------------------------------------------------------------------------- 

2# Copyright (c) 2008 by David P. D. Moss. All rights reserved. 

3# 

4# Released under the BSD license. See the LICENSE file for details. 

5#----------------------------------------------------------------------------- 

6"""A basic implementation of RFC 1924 ;-)""" 

7 

8from netaddr.core import AddrFormatError 

9from netaddr.ip import IPAddress 

10 

11from netaddr.compat import _zip 

12 

13 

14def chr_range(low, high): 

15 """Returns all characters between low and high chars.""" 

16 return [chr(i) for i in range(ord(low), ord(high) + 1)] 

17 

18#: Base 85 integer index to character lookup table. 

19BASE_85 = ( 

20 chr_range('0', '9') + chr_range('A', 'Z') + 

21 chr_range('a', 'z') + 

22 ['!', '#', '$', '%', '&', '(', ')', '*', '+', '-', ';', '<', '=', '>', 

23 '?', '@', '^', '_', '`', '{', '|', '}', '~'] 

24) 

25 

26#: Base 85 digit to integer lookup table. 

27BASE_85_DICT = dict(_zip(BASE_85, range(0, 86))) 

28 

29 

30def ipv6_to_base85(addr): 

31 """Convert a regular IPv6 address to base 85.""" 

32 ip = IPAddress(addr) 

33 int_val = int(ip) 

34 

35 remainder = [] 

36 while int_val > 0: 

37 remainder.append(int_val % 85) 

38 int_val //= 85 

39 

40 encoded = ''.join([BASE_85[w] for w in reversed(remainder)]) 

41 leading_zeroes = (20 - len(encoded)) * "0" 

42 return leading_zeroes + encoded 

43 

44 

45def base85_to_ipv6(addr): 

46 """ 

47 Convert a base 85 IPv6 address to its hexadecimal format. 

48 """ 

49 tokens = list(addr) 

50 

51 if len(tokens) != 20: 

52 raise AddrFormatError('Invalid base 85 IPv6 address: %r' % (addr,)) 

53 

54 result = 0 

55 for i, num in enumerate(reversed(tokens)): 

56 num = BASE_85_DICT[num] 

57 result += (num * 85 ** i) 

58 

59 ip = IPAddress(result, 6) 

60 

61 return str(ip)