-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
60 lines (53 loc) · 2.49 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# MIT License
#
# Copyright (c) 2023 Jack Hart
#
# 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 __future__ import annotations
import hashlib
import socket
import sys
from ipaddress import ip_address, IPv4Address, IPv6Address
def file_cache(filename):
"""Save the contents of a file to a cache, and only run the decorated function if the file has changed.
This still has the overhead of reading the file.
"""
def file_cache_wrapper(func):
cache = {'last_hash': None, 'result': None}
def wrapper():
with open(filename, 'r') as f:
content = f.read()
new_hash = hashlib.md5(content.encode()).hexdigest()
if new_hash != cache['last_hash']:
cache['result'] = func()
cache['last_hash'] = new_hash
return cache['result']
return wrapper
return file_cache_wrapper
def host_hex_to_ip(hex_val: str) -> IPv4Address | IPv6Address:
"""Convert a hex string in network byte order (big-endian) to IP address object."""
# Convert hex string to bytes
net_order = bytes.fromhex(hex_val)
net_order = net_order if sys.byteorder == 'big' else net_order[::-1]
if len(net_order) == 4: # IPv4 address
return ip_address(socket.inet_ntop(socket.AF_INET, net_order))
elif len(net_order) == 16: # IPv6 address
return ip_address(socket.inet_ntop(socket.AF_INET6, net_order))
else:
raise ValueError(f"Invalid IP address length: {len(net_order)}")