Add length and length_raw attributes to Resource (closes #3)

For compressed resources, the value of the length attribute can be
accessed much more quickly than the data itself (because it only
requires parsing the header, rather than decompressing the entire
data). This is used to speed up listing of compressed resources on the
command line.

The length_raw attribute is added for symmetry, although it is not
specifically optimized in any case yet.
This commit is contained in:
dgelessus 2019-09-24 00:13:23 +02:00
parent 0c942e26ec
commit c108af60ca
2 changed files with 25 additions and 4 deletions

View File

@ -197,13 +197,13 @@ def _describe_resource(res: api.Resource, *, include_type: bool, decompress: boo
if decompress and api.ResourceAttrs.resCompressed in res.attributes:
try:
res.data
res.compressed_info
except compress.DecompressError:
length_desc = f"decompression failed ({len(res.data_raw)} bytes compressed)"
length_desc = f"decompression failed ({res.length_raw} bytes compressed)"
else:
length_desc = f"{len(res.data)} bytes ({len(res.data_raw)} bytes compressed)"
length_desc = f"{res.length} bytes ({res.length_raw} bytes compressed)"
else:
length_desc = f"{len(res.data_raw)} bytes"
length_desc = f"{res.length_raw} bytes"
content_desc_parts.append(length_desc)
attrs = _decompose_flags(res.attributes)

View File

@ -154,6 +154,27 @@ class Resource(object):
else:
return None
@property
def length_raw(self) -> int:
"""The length of the raw resource data, which may be compressed.
Accessing this attribute may be faster than computing len(self.data_raw) manually.
"""
return len(self.data_raw)
@property
def length(self) -> int:
"""The length of the resource data. If the resource data is compressed, this is the length of the data after decompression.
Accessing this attribute may be faster than computing len(self.data) manually.
"""
if ResourceAttrs.resCompressed in self.attributes:
return self.compressed_info.decompressed_length
else:
return self.length_raw
@property
def data(self) -> bytes:
"""The resource data, decompressed if necessary.