Created
August 26, 2021 18:12
-
-
Save FFY00/c80d84f2a0a3bd17e09d3bb766d8f340 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Memory(): | |
@dataclasses.dataclass | |
class Pool(): | |
offset: int | |
size: int | |
def __contains__(self, other: Any) -> bool: | |
return isinstance(other, int) and self.offset <= other <= (self.offset + self.size) | |
def __init__(self, default_align: int = 0) -> None: | |
self._default_align = default_align | |
self._data = bytearray() | |
self._free: List[_Memory.Pool] = [] | |
def __bytes__(self) -> bytes: | |
return bytes(self._data) | |
def __len__(self) -> int: | |
return self._tail | |
@property | |
def data(self) -> bytearray: | |
return self._data.copy() | |
@property | |
def _tail(self) -> int: | |
return len(self._data) | |
def _align(self, address: int, align_number: int) -> int: | |
if align_number == 0: | |
return address | |
unaligned_bytes = address % align_number | |
if unaligned_bytes == 0: | |
return address | |
return address + (align_number - unaligned_bytes) | |
def write(self, data_object: Union[bytes, _IntoBytes], align: Optional[int] = None) -> int: | |
if align is None: | |
align = self._default_align | |
assert align is not None | |
data = bytes(data_object) | |
write_size = len(data) | |
# try one of the free memory polls first | |
for pool in self._free.copy(): | |
write_offset = self._align(pool.offset, align) | |
if write_offset not in pool: | |
print('> found free! writting to', hex(write_offset)) | |
self._data[write_offset:write_size] = data | |
self._free.remove(pool) | |
return write_offset | |
# write to the tail | |
write_offset = self._align(self._tail, align) | |
if write_offset > self._tail: # add skipped memory to the free memory pool list | |
skip_bytes = write_offset - self._tail | |
self._free.append(self.Pool(self._tail, skip_bytes)) | |
print('> skiping from', hex(self._tail), 'to', hex(write_offset - 1), f'(align to {hex(align)})') | |
self._data += b'\x00' * skip_bytes | |
print('> writting to', hex(write_offset)) | |
self._data[write_offset:write_size] = data | |
return write_offset |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment