Skip to content

Commit

Permalink
feat(utils): add readable, writable, and seekable functions to File c…
Browse files Browse the repository at this point in the history
…lass.

These functions are required for pyFatFS to work.
  • Loading branch information
qkaiser committed Sep 4, 2023
1 parent 313351e commit f847623
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
16 changes: 15 additions & 1 deletion unblob/file_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,18 +41,23 @@ class SeekError(ValueError):


class File(mmap.mmap):
access: int

@classmethod
def from_bytes(cls, content: bytes):
m = cls(-1, len(content))
m.write(content)
m.seek(0)
m.access = mmap.ACCESS_WRITE
return m

@classmethod
def from_path(cls, path: Path, access=mmap.ACCESS_READ):
mode = "r+b" if access == mmap.ACCESS_WRITE else "rb"
with path.open(mode) as base_file:
return cls(base_file.fileno(), 0, access=access)
m = cls(base_file.fileno(), 0, access=access)
m.access = access
return m

def seek(self, pos: int, whence: int = os.SEEK_SET) -> int:
try:
Expand Down Expand Up @@ -81,6 +86,15 @@ def __enter__(self):
def __exit__(self, _exc_type, _exc_val, _exc_tb):
self.close()

def readable(self) -> bool:
return self.access in (mmap.ACCESS_READ, mmap.ACCESS_COPY)

def writable(self) -> bool:
return self.access in (mmap.ACCESS_WRITE, mmap.ACCESS_COPY)

def seekable(self) -> bool:
return True # Memory-mapped files are always seekable


class OffsetFile:
def __init__(self, file: File, offset: int):
Expand Down
3 changes: 3 additions & 0 deletions vulture_whitelist.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@

unblob.plugins.hookimpl
File.from_bytes
File.readable
File.writable
File.seekable
FileSystem.open

iterbits
Expand Down

0 comments on commit f847623

Please sign in to comment.