find.py
1 # SPDX-FileCopyrightText: 2019 4am 2 # 3 # SPDX-License-Identifier: MIT 4 5 import re 6 7 WILDCARD = b'\x97' 8 WILDSTR = "97" 9 10 def wild(source_bytes, search_bytes): 11 """Search source_bytes (bytes object) for the first instance of search_bytes (bytes_object). search_bytes may contain WILDCARD, which matches any single byte (like "." in a regular expression). Returns index of first match, or -1 if no matches.""" 12 search_bytes = re.escape(search_bytes).replace(WILDCARD, b'.') 13 match = re.search(search_bytes, source_bytes) 14 if match: 15 return match.start() 16 return -1 17 18 def wild_at(offset, source_bytes, search_bytes): 19 """returns True if the search_bytes was found in source_bytes at offset (search_bytes may include wildcards), otherwise False""" 20 offset = wild(source_bytes[offset:], search_bytes) 21 return offset == 0 22 23 def at(offset, source_bytes, search_bytes): 24 """returns True if the exact bytes search_bytes was found in source_bytes at offset (no wildcards), otherwise False""" 25 return source_bytes[offset:offset+len(search_bytes)] == search_bytes