Skip to content

Commit 9de46ee

Browse files
committed
secondary seeking optimisation (precomputation)
1 parent 0518de7 commit 9de46ee

File tree

1 file changed

+6
-9
lines changed

1 file changed

+6
-9
lines changed

kaitaistruct.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ class KaitaiStream(object):
6565
def __init__(self, io):
6666
self._io = io
6767
self.align_to_byte()
68+
self.precompute_size()
6869

6970
def __enter__(self):
7071
return self
@@ -95,21 +96,17 @@ def pos(self):
9596
return self._io.tell()
9697

9798
def size(self):
98-
if hasattr(self, 'size_cached'):
99-
return self.size_cached
99+
# Further optimisation: make `size()` into `size`, requires compiler coop.
100+
return self.size_cached
101+
102+
def precompute_size(self):
100103
# Python has no internal File object API function to get
101-
# current file / StringIO size, thus we use the following
102-
# trick.
104+
# current file / StringIO size, thus we use the following trick.
103105
io = self._io
104-
# Remember our current position
105106
cur_pos = io.tell()
106-
# Seek to the end of the File object
107-
# Remember position, which is equal to the full length
108107
full_size = io.seek(0, SEEK_END)
109-
# Seek back to the current position
110108
io.seek(cur_pos)
111109
self.size_cached = full_size
112-
return full_size
113110

114111
# ========================================================================
115112
# Integer numbers

0 commit comments

Comments
 (0)