cs-buffer 20240412__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cs/buffer.py
ADDED
|
@@ -0,0 +1,1374 @@
|
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
#
|
|
3
|
+
# Functions associated with bytes, bytearrays, memoryviews and buffers in general.
|
|
4
|
+
# Also CornuCopyBuffer for managing a buffer and an input source.
|
|
5
|
+
# - Cameron Simpson <cs@cskk.id.au> 18mar2017
|
|
6
|
+
#
|
|
7
|
+
# pylint: disable=too-many-lines
|
|
8
|
+
#
|
|
9
|
+
|
|
10
|
+
''' Facilities to do with buffers, particularly CornuCopyBuffer,
|
|
11
|
+
an automatically refilling buffer to support parsing of data streams.
|
|
12
|
+
'''
|
|
13
|
+
|
|
14
|
+
from contextlib import contextmanager
|
|
15
|
+
import os
|
|
16
|
+
from os import fstat, SEEK_SET, SEEK_CUR, SEEK_END
|
|
17
|
+
import mmap
|
|
18
|
+
from stat import S_ISREG
|
|
19
|
+
import sys
|
|
20
|
+
from threading import Thread
|
|
21
|
+
|
|
22
|
+
from cs.deco import Promotable
|
|
23
|
+
from cs.gimmicks import r
|
|
24
|
+
from cs.py3 import pread
|
|
25
|
+
|
|
26
|
+
__version__ = '20240412'
|
|
27
|
+
|
|
28
|
+
DISTINFO = {
|
|
29
|
+
'keywords': ["python3"],
|
|
30
|
+
'classifiers': [
|
|
31
|
+
"Programming Language :: Python",
|
|
32
|
+
"Programming Language :: Python :: 3",
|
|
33
|
+
"Development Status :: 5 - Production/Stable",
|
|
34
|
+
],
|
|
35
|
+
'install_requires': ['cs.deco', 'cs.gimmicks', 'cs.py3'],
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
DEFAULT_READSIZE = 131072
|
|
39
|
+
|
|
40
|
+
MEMORYVIEW_THRESHOLD = DEFAULT_READSIZE # tweak if this gets larger
|
|
41
|
+
|
|
42
|
+
# pylint: disable=too-many-public-methods,too-many-instance-attributes
|
|
43
|
+
class CornuCopyBuffer(Promotable):
|
|
44
|
+
''' An automatically refilling buffer intended to support parsing
|
|
45
|
+
of data streams.
|
|
46
|
+
|
|
47
|
+
Its purpose is to aid binary parsers
|
|
48
|
+
which do not themselves need to handle sources specially;
|
|
49
|
+
`CornuCopyBuffer`s are trivially made from `bytes`,
|
|
50
|
+
iterables of `bytes` and file-like objects.
|
|
51
|
+
See `cs.binary` for convenient parsing classes
|
|
52
|
+
which work against `CornuCopyBuffer`s.
|
|
53
|
+
|
|
54
|
+
Attributes:
|
|
55
|
+
* `buf`: the first of any buffered leading chunks
|
|
56
|
+
buffer of unparsed data from the input, available
|
|
57
|
+
for direct inspection by parsers;
|
|
58
|
+
normally however parsers will use `.extend` and `.take`.
|
|
59
|
+
* `offset`: the logical offset of the buffer; this excludes
|
|
60
|
+
buffered data and unconsumed input data
|
|
61
|
+
|
|
62
|
+
*Note*: the initialiser may supply a cleanup function;
|
|
63
|
+
although this will be called via the buffer's `.__del__` method
|
|
64
|
+
a prudent user of a buffer should call the `.close()` method
|
|
65
|
+
when finished with the buffer to ensure prompt cleanup.
|
|
66
|
+
|
|
67
|
+
The primary methods supporting parsing of data streams are
|
|
68
|
+
`.extend()` and `take()`.
|
|
69
|
+
Calling `.extend(min_size)` arranges that the internal buffer
|
|
70
|
+
contains at least `min_size` bytes.
|
|
71
|
+
Calling `.take(size)` fetches exactly `size` bytes from the
|
|
72
|
+
internal buffer and the input source if necessary and returns
|
|
73
|
+
them, adjusting the internal buffer.
|
|
74
|
+
|
|
75
|
+
len(`CornuCopyBuffer`) returns the length of any buffered data.
|
|
76
|
+
|
|
77
|
+
bool(`CornuCopyBuffer`) tests whether len() > 0.
|
|
78
|
+
|
|
79
|
+
Indexing a `CornuCopyBuffer` accesses the buffered data only,
|
|
80
|
+
returning an individual byte's value (an `int`).
|
|
81
|
+
|
|
82
|
+
A `CornuCopyBuffer` is also iterable, yielding data in whatever
|
|
83
|
+
sizes come from its `input_data` source, preceeded by any
|
|
84
|
+
content in the internal buffer.
|
|
85
|
+
|
|
86
|
+
A `CornuCopyBuffer` also supports the file methods `.read`,
|
|
87
|
+
`.tell` and `.seek` supporting drop in use of the buffer in
|
|
88
|
+
many file contexts. Backward seeks are not supported. `.seek`
|
|
89
|
+
will take advantage of the `input_data`'s .seek method if it
|
|
90
|
+
has one, otherwise it will use consume the `input_data`
|
|
91
|
+
as required.
|
|
92
|
+
'''
|
|
93
|
+
|
|
94
|
+
# pylint: disable=too-many-arguments
|
|
95
|
+
def __init__(
|
|
96
|
+
self,
|
|
97
|
+
input_data,
|
|
98
|
+
buf=None,
|
|
99
|
+
offset=0,
|
|
100
|
+
seekable=None,
|
|
101
|
+
copy_offsets=None,
|
|
102
|
+
copy_chunks=None,
|
|
103
|
+
close=None,
|
|
104
|
+
progress=None,
|
|
105
|
+
):
|
|
106
|
+
''' Prepare the buffer.
|
|
107
|
+
|
|
108
|
+
Parameters:
|
|
109
|
+
* `input_data`: an iterable of data chunks (`bytes`-like instances);
|
|
110
|
+
if your data source is a file see the `.from_file` factory;
|
|
111
|
+
if your data source is a file descriptor see the `.from_fd`
|
|
112
|
+
factory.
|
|
113
|
+
* `buf`: if not `None`, the initial state of the parse buffer
|
|
114
|
+
* `offset`: logical offset of the start of the buffer, default `0`
|
|
115
|
+
* `seekable`: whether `input_data` has a working `.seek` method;
|
|
116
|
+
the default is `None` meaning that it will be attempted on
|
|
117
|
+
the first skip or seek
|
|
118
|
+
* `copy_offsets`: if not `None`, a callable for parsers to
|
|
119
|
+
report pertinent offsets via the buffer's `.report_offset`
|
|
120
|
+
method
|
|
121
|
+
* `copy_chunks`: if not `None`, every fetched data chunk is
|
|
122
|
+
copied to this callable
|
|
123
|
+
|
|
124
|
+
The `input_data` is an iterable whose iterator may have
|
|
125
|
+
some optional additional properties:
|
|
126
|
+
* `seek`: if present, this is a seek method after the fashion
|
|
127
|
+
of `file.seek`; the buffer's `seek`, `skip` and `skipto`
|
|
128
|
+
methods will take advantage of this if available.
|
|
129
|
+
* `offset`: the current byte offset of the iterator; this
|
|
130
|
+
is used during the buffer initialisation to compute
|
|
131
|
+
`input_data_displacement`, the difference between the
|
|
132
|
+
buffer's logical offset and the input data iterable's logical offset;
|
|
133
|
+
if unavailable during initialisation this is presumed to
|
|
134
|
+
be `0`.
|
|
135
|
+
* `end_offset`: the end offset of the iterator if known.
|
|
136
|
+
* `close`: an optional callable
|
|
137
|
+
that may be provided for resource cleanup
|
|
138
|
+
when the user of the buffer calls its `.close()` method.
|
|
139
|
+
* `progress`: an optional `cs.Progress.progress` instance
|
|
140
|
+
to which to report data consumed from `input_data`;
|
|
141
|
+
any object supporting `+=` is acceptable
|
|
142
|
+
'''
|
|
143
|
+
self.bufs = []
|
|
144
|
+
if buf is None or not buf:
|
|
145
|
+
self.buflen = 0
|
|
146
|
+
else:
|
|
147
|
+
self.bufs.append(buf)
|
|
148
|
+
self.buflen = len(buf)
|
|
149
|
+
self.offset = offset
|
|
150
|
+
self.seekable = seekable
|
|
151
|
+
input_data = iter(input_data)
|
|
152
|
+
if copy_chunks is not None:
|
|
153
|
+
input_data = CopyingIterator(input_data, copy_chunks)
|
|
154
|
+
self.input_data = input_data
|
|
155
|
+
self.copy_offsets = copy_offsets
|
|
156
|
+
# Try to compute the displacement between the input_data byte
|
|
157
|
+
# offset and the buffer's logical offset.
|
|
158
|
+
# NOTE: if the input_data iterator does not have a .offset
|
|
159
|
+
# attribute then we assume the iterator byte offset is 0, purely
|
|
160
|
+
# to reduce the burden on iterator implementors.
|
|
161
|
+
input_offset = getattr(input_data, 'offset', 0)
|
|
162
|
+
self.input_offset_displacement = input_offset - offset
|
|
163
|
+
self._close = close
|
|
164
|
+
self.progress = progress
|
|
165
|
+
|
|
166
|
+
def selfcheck(self, msg=''):
|
|
167
|
+
''' Integrity check for the buffer, useful during debugging.
|
|
168
|
+
'''
|
|
169
|
+
msgpfx = type(self).__name__ + '.selfcheck'
|
|
170
|
+
if msg:
|
|
171
|
+
msgpfx += ': ' + msg
|
|
172
|
+
msgpfx += "buflen=%d, bufs=%r" % (
|
|
173
|
+
self.buflen, [len(buf) for buf in self.bufs]
|
|
174
|
+
)
|
|
175
|
+
assert self.buflen == sum(
|
|
176
|
+
len(buf) for buf in self.bufs
|
|
177
|
+
), msgpfx + ": self.buflen != sum of .bufs"
|
|
178
|
+
assert all(
|
|
179
|
+
len(buf) > 0 for buf in self.bufs
|
|
180
|
+
), msgpfx + ": not all .bufs are nonempty"
|
|
181
|
+
|
|
182
|
+
@property
|
|
183
|
+
def buf(self):
|
|
184
|
+
''' The first buffer, or `b''` if nothing is buffered.
|
|
185
|
+
'''
|
|
186
|
+
try:
|
|
187
|
+
return self.bufs[0]
|
|
188
|
+
except IndexError:
|
|
189
|
+
return b''
|
|
190
|
+
|
|
191
|
+
def close(self):
|
|
192
|
+
''' Close the buffer.
|
|
193
|
+
This calls the `close` callable supplied
|
|
194
|
+
when the buffer was initialised, if any,
|
|
195
|
+
in order to release resources such as open file descriptors.
|
|
196
|
+
The callable will be called only on the first `close()` call.
|
|
197
|
+
|
|
198
|
+
*Note*: this does *not* prevent subsequent reads or iteration
|
|
199
|
+
from the buffer; it is only for resource cleanup,
|
|
200
|
+
though that cleanup might itself break iteration.
|
|
201
|
+
'''
|
|
202
|
+
if self._close:
|
|
203
|
+
self._close()
|
|
204
|
+
self._close = None
|
|
205
|
+
|
|
206
|
+
def __del__(self):
|
|
207
|
+
''' Release resources when the object is deleted.
|
|
208
|
+
'''
|
|
209
|
+
self.close()
|
|
210
|
+
|
|
211
|
+
@classmethod
|
|
212
|
+
def from_fd(cls, fd, readsize=None, offset=None, **kw):
|
|
213
|
+
''' Return a new `CornuCopyBuffer` attached to an open file descriptor.
|
|
214
|
+
|
|
215
|
+
Internally this constructs a `SeekableFDIterator` for regular
|
|
216
|
+
files or an `FDIterator` for other files, which provides the
|
|
217
|
+
iteration that `CornuCopyBuffer` consumes, but also seek
|
|
218
|
+
support if the underlying file descriptor is seekable.
|
|
219
|
+
|
|
220
|
+
*Note*: a `SeekableFDIterator` makes an `os.dup` of the
|
|
221
|
+
supplied file descriptor, so the caller is responsible for
|
|
222
|
+
closing the original.
|
|
223
|
+
|
|
224
|
+
Parameters:
|
|
225
|
+
* `fd`: the operating system file descriptor
|
|
226
|
+
* `readsize`: an optional preferred read size
|
|
227
|
+
* `offset`: a starting position for the data; the file
|
|
228
|
+
descriptor will seek to this offset, and the buffer will
|
|
229
|
+
start with this offset
|
|
230
|
+
Other keyword arguments are passed to the buffer constructor.
|
|
231
|
+
'''
|
|
232
|
+
if S_ISREG(fstat(fd).st_mode):
|
|
233
|
+
it = SeekableFDIterator(fd, readsize=readsize, offset=offset)
|
|
234
|
+
else:
|
|
235
|
+
it = FDIterator(fd, readsize=readsize, offset=offset)
|
|
236
|
+
return cls(it, offset=it.offset, close=it.close, **kw)
|
|
237
|
+
|
|
238
|
+
def as_fd(self, maxlength=Ellipsis):
|
|
239
|
+
''' Create a pipe and dispatch a `Thread` to copy
|
|
240
|
+
up to `maxlength` bytes from `bfr` into it.
|
|
241
|
+
Return the file descriptor of the read end of the pipe.
|
|
242
|
+
|
|
243
|
+
The default `maxlength` is `Ellipsis`, meaning to copy all data.
|
|
244
|
+
|
|
245
|
+
Note that the thread preemptively consumes from the buffer.
|
|
246
|
+
|
|
247
|
+
This is useful for passing buffer data to subprocesses.
|
|
248
|
+
'''
|
|
249
|
+
rfd, wfd = os.pipe()
|
|
250
|
+
|
|
251
|
+
def copy_buffer():
|
|
252
|
+
''' Copy data from the buffer to `wfd`,
|
|
253
|
+
closing `wfd` when finished.
|
|
254
|
+
'''
|
|
255
|
+
try:
|
|
256
|
+
for bs in self.iter(maxlength):
|
|
257
|
+
while bs:
|
|
258
|
+
try:
|
|
259
|
+
nbs = os.write(wfd, bs)
|
|
260
|
+
except OSError:
|
|
261
|
+
# rebuffer uncopied data and reraise
|
|
262
|
+
self.push(bs)
|
|
263
|
+
raise
|
|
264
|
+
bs = bs[nbs:]
|
|
265
|
+
finally:
|
|
266
|
+
os.close(wfd)
|
|
267
|
+
|
|
268
|
+
Thread(
|
|
269
|
+
name="%s.copy_to_fd_%d_as_%d" % (self, wfd, rfd), target=copy_buffer
|
|
270
|
+
).start()
|
|
271
|
+
return rfd
|
|
272
|
+
|
|
273
|
+
@classmethod
|
|
274
|
+
def from_mmap(cls, fd, readsize=None, offset=None, **kw):
|
|
275
|
+
''' Return a new `CornuCopyBuffer` attached to an mmap of an open
|
|
276
|
+
file descriptor.
|
|
277
|
+
|
|
278
|
+
Internally this constructs a `SeekableMMapIterator`, which
|
|
279
|
+
provides the iteration that `CornuCopyBuffer` consumes, but
|
|
280
|
+
also seek support.
|
|
281
|
+
|
|
282
|
+
*Note*: a `SeekableMMapIterator` makes an `os.dup` of the
|
|
283
|
+
supplied file descriptor, so the caller is responsible for
|
|
284
|
+
closing the original.
|
|
285
|
+
|
|
286
|
+
Parameters:
|
|
287
|
+
* `fd`: the operating system file descriptor
|
|
288
|
+
* `readsize`: an optional preferred read size
|
|
289
|
+
* `offset`: a starting position for the data; the file
|
|
290
|
+
descriptor will seek to this offset, and the buffer will
|
|
291
|
+
start with this offset
|
|
292
|
+
Other keyword arguments are passed to the buffer constructor.
|
|
293
|
+
'''
|
|
294
|
+
it = SeekableMMapIterator(fd, readsize=readsize, offset=offset)
|
|
295
|
+
return cls(it, offset=it.offset, **kw)
|
|
296
|
+
|
|
297
|
+
@classmethod
|
|
298
|
+
def from_file(cls, f, readsize=None, offset=None, **kw):
|
|
299
|
+
''' Return a new `CornuCopyBuffer` attached to an open file.
|
|
300
|
+
|
|
301
|
+
Internally this constructs a `SeekableFileIterator`, which
|
|
302
|
+
provides the iteration that `CornuCopyBuffer` consumes
|
|
303
|
+
and also seek support if the underlying file is seekable.
|
|
304
|
+
|
|
305
|
+
Parameters:
|
|
306
|
+
* `f`: the file like object
|
|
307
|
+
* `readsize`: an optional preferred read size
|
|
308
|
+
* `offset`: a starting position for the data; the file
|
|
309
|
+
will seek to this offset, and the buffer will start with this
|
|
310
|
+
offset
|
|
311
|
+
Other keyword arguments are passed to the buffer constructor.
|
|
312
|
+
'''
|
|
313
|
+
try:
|
|
314
|
+
ftell = f.tell
|
|
315
|
+
except AttributeError:
|
|
316
|
+
is_seekable = False
|
|
317
|
+
foffset = None
|
|
318
|
+
else:
|
|
319
|
+
try:
|
|
320
|
+
foffset = ftell()
|
|
321
|
+
except OSError:
|
|
322
|
+
is_seekable = False
|
|
323
|
+
foffset = None
|
|
324
|
+
else:
|
|
325
|
+
is_seekable = True
|
|
326
|
+
if offset is None:
|
|
327
|
+
offset = foffset
|
|
328
|
+
it = (
|
|
329
|
+
SeekableFileIterator(f, readsize=readsize, offset=offset)
|
|
330
|
+
if is_seekable else FileIterator(f, readsize=readsize, offset=offset)
|
|
331
|
+
)
|
|
332
|
+
return cls(it, offset=it.offset, **kw)
|
|
333
|
+
|
|
334
|
+
@classmethod
|
|
335
|
+
def from_filename(cls, filename: str, offset=None, **kw):
|
|
336
|
+
''' Open the file named `filename` and return a new `CornuCopyBuffer`.
|
|
337
|
+
|
|
338
|
+
If `offset` is provided, skip to that position in the file.
|
|
339
|
+
A negative offset skips to a position that far from the end of the file
|
|
340
|
+
as determined by its `Stat.st_size`.
|
|
341
|
+
|
|
342
|
+
Other keyword arguments are passed to the buffer constructor.
|
|
343
|
+
'''
|
|
344
|
+
f = open(filename, 'rb') # pylint: disable=consider-using-with
|
|
345
|
+
bfr = cls.from_file(f, close=f.close, **kw)
|
|
346
|
+
if offset is not None:
|
|
347
|
+
if offset < 0:
|
|
348
|
+
S = os.fstat(f.fileno())
|
|
349
|
+
offset2 = S.st_size + offset
|
|
350
|
+
if offset2 < 0:
|
|
351
|
+
raise ValueError(
|
|
352
|
+
"offset %s is too far from the end of the file (st_size=%s)" %
|
|
353
|
+
(offset, S.st_size)
|
|
354
|
+
)
|
|
355
|
+
bfr.skipto(offset)
|
|
356
|
+
return bfr
|
|
357
|
+
|
|
358
|
+
@classmethod
|
|
359
|
+
def from_bytes(cls, bs, offset=0, length=None, **kw):
|
|
360
|
+
''' Return a `CornuCopyBuffer` fed from the supplied bytes `bs`
|
|
361
|
+
starting at `offset` and ending after `length`.
|
|
362
|
+
|
|
363
|
+
This is handy for callers parsing using buffers but handed bytes.
|
|
364
|
+
|
|
365
|
+
Parameters:
|
|
366
|
+
* `bs`: the bytes
|
|
367
|
+
* `offset`: a starting position for the data; the input
|
|
368
|
+
data will start this far into the bytes
|
|
369
|
+
* `length`: the maximium number of bytes to use; the input
|
|
370
|
+
data will be cropped this far past the starting point;
|
|
371
|
+
default: the number of bytes in `bs` after `offset`
|
|
372
|
+
Other keyword arguments are passed to the buffer constructor.
|
|
373
|
+
'''
|
|
374
|
+
if offset < 0:
|
|
375
|
+
raise ValueError("offset(%d) should be >= 0" % (offset,))
|
|
376
|
+
if offset > len(bs):
|
|
377
|
+
raise ValueError(
|
|
378
|
+
"offset(%d) beyond end of bs (%d bytes)" % (offset, len(bs))
|
|
379
|
+
)
|
|
380
|
+
if length is None:
|
|
381
|
+
length = len(bs) - offset
|
|
382
|
+
else:
|
|
383
|
+
# sanity check supplied length
|
|
384
|
+
if length < 1:
|
|
385
|
+
raise ValueError("length(%d) < 1" % (length,))
|
|
386
|
+
end_offset = offset + length
|
|
387
|
+
if end_offset > len(bs):
|
|
388
|
+
raise ValueError(
|
|
389
|
+
"offset(%d)+length(%d) > len(bs):%d" % (offset, length, len(bs))
|
|
390
|
+
)
|
|
391
|
+
bs = memoryview(bs)
|
|
392
|
+
if offset > 0 or end_offset < len(bs):
|
|
393
|
+
bs = bs[offset:end_offset]
|
|
394
|
+
return cls([bs], offset=offset, **kw)
|
|
395
|
+
|
|
396
|
+
def __str__(self):
|
|
397
|
+
return "%s(offset:%d,buf:%d)" % (
|
|
398
|
+
type(self).__name__, self.offset, self.buflen
|
|
399
|
+
)
|
|
400
|
+
|
|
401
|
+
def __len__(self):
|
|
402
|
+
''' The length is the length of the internal buffer: data available without a fetch.
|
|
403
|
+
'''
|
|
404
|
+
return self.buflen
|
|
405
|
+
|
|
406
|
+
def __bool__(self):
|
|
407
|
+
return len(self) > 0
|
|
408
|
+
|
|
409
|
+
__nonzero__ = __bool__
|
|
410
|
+
|
|
411
|
+
def __getitem__(self, index):
|
|
412
|
+
''' Fetch from the internal buffer.
|
|
413
|
+
This does not consume data from the internal buffer.
|
|
414
|
+
Note that this is an expensive way to access the buffer,
|
|
415
|
+
particularly if `index` is a slice.
|
|
416
|
+
|
|
417
|
+
If `index` is a `slice`, slice the join of the internal subbuffers.
|
|
418
|
+
This is quite expensive
|
|
419
|
+
and it is probably better to `take` or `takev`
|
|
420
|
+
some data from the buffer.
|
|
421
|
+
|
|
422
|
+
Otherwise `index` should be an `int` and the corresponding
|
|
423
|
+
buffered byte is returned.
|
|
424
|
+
|
|
425
|
+
This is usually not a very useful method;
|
|
426
|
+
its primary use case is to probe the buffer to make a parsing decision
|
|
427
|
+
instead of taking a byte off and (possibly) pushing it back.
|
|
428
|
+
'''
|
|
429
|
+
if isinstance(index, slice):
|
|
430
|
+
# slice the joined up bufs - expensive
|
|
431
|
+
return b''.join(self.bufs)[index]
|
|
432
|
+
index0 = index
|
|
433
|
+
if index < 0:
|
|
434
|
+
index = self.buflen - index
|
|
435
|
+
if index < 0:
|
|
436
|
+
raise IndexError(
|
|
437
|
+
"index %s out of range (buflen=%d)" % (index0, self.buflen)
|
|
438
|
+
)
|
|
439
|
+
if index >= self.buflen:
|
|
440
|
+
raise IndexError(
|
|
441
|
+
"index %s out of range (buflen=%d)" % (index0, self.buflen)
|
|
442
|
+
)
|
|
443
|
+
buf_offset = 0
|
|
444
|
+
for buf in self.bufs:
|
|
445
|
+
if index < buf_offset + len(buf):
|
|
446
|
+
return buf[index - buf_offset]
|
|
447
|
+
buf_offset += len(buf)
|
|
448
|
+
raise RuntimeError(
|
|
449
|
+
"%s.__getitem__(%s): failed to locate byte in bufs %r" %
|
|
450
|
+
(self, index0, [len(buf) for buf in self.bufs])
|
|
451
|
+
)
|
|
452
|
+
|
|
453
|
+
def __iter__(self):
|
|
454
|
+
return self
|
|
455
|
+
|
|
456
|
+
def __next__(self):
|
|
457
|
+
''' Fetch a data chunk from the buffer.
|
|
458
|
+
'''
|
|
459
|
+
if self.bufs:
|
|
460
|
+
chunk = self.bufs.pop(0)
|
|
461
|
+
self.buflen -= len(chunk)
|
|
462
|
+
else:
|
|
463
|
+
chunk = next(self.input_data)
|
|
464
|
+
if self.progress is not None:
|
|
465
|
+
self.progress += len(chunk)
|
|
466
|
+
self.offset += len(chunk)
|
|
467
|
+
return chunk
|
|
468
|
+
|
|
469
|
+
next = __next__
|
|
470
|
+
|
|
471
|
+
def iter(self, maxlength):
|
|
472
|
+
''' Yield chunks from the buffer
|
|
473
|
+
up to `maxlength` in total
|
|
474
|
+
or until EOF if `maxlength` is `Ellipsis`.
|
|
475
|
+
'''
|
|
476
|
+
if maxlength is not Ellipsis and maxlength < 1:
|
|
477
|
+
raise ValueError(
|
|
478
|
+
"maxlength mst be Ellipsis or >=1, got %r" % (maxlength,)
|
|
479
|
+
)
|
|
480
|
+
while maxlength is Ellipsis or maxlength > 0:
|
|
481
|
+
try:
|
|
482
|
+
bs = next(self)
|
|
483
|
+
except StopIteration:
|
|
484
|
+
break
|
|
485
|
+
if maxlength is not Ellipsis:
|
|
486
|
+
if maxlength < len(bs):
|
|
487
|
+
self.push(bs[maxlength:])
|
|
488
|
+
bs = bs[:maxlength]
|
|
489
|
+
maxlength -= len(bs)
|
|
490
|
+
yield bs
|
|
491
|
+
|
|
492
|
+
def push(self, bs):
|
|
493
|
+
''' Push the chunk `bs` onto the front of the buffered data.
|
|
494
|
+
Rewinds the logical `.offset` by the length of `bs`.
|
|
495
|
+
'''
|
|
496
|
+
blen = len(bs)
|
|
497
|
+
if blen > 0:
|
|
498
|
+
self.bufs.insert(0, bs)
|
|
499
|
+
self.buflen += blen
|
|
500
|
+
self.offset -= blen
|
|
501
|
+
|
|
502
|
+
@property
|
|
503
|
+
def end_offset(self):
|
|
504
|
+
''' Return the end offset of the input data (in buffer ordinates)
|
|
505
|
+
if known, otherwise `None`.
|
|
506
|
+
|
|
507
|
+
Note that this depends on the computation of the
|
|
508
|
+
`input_offset_displacement` which takes place at the buffer
|
|
509
|
+
initialisation, which in turn relies on the `input_data.offset`
|
|
510
|
+
attribute, which at initialisation is presumed to be 0 if missing.
|
|
511
|
+
'''
|
|
512
|
+
input_data = self.input_data
|
|
513
|
+
try:
|
|
514
|
+
input_end_offset = input_data.end_offset
|
|
515
|
+
except AttributeError:
|
|
516
|
+
return None
|
|
517
|
+
return input_end_offset - self.input_offset_displacement
|
|
518
|
+
|
|
519
|
+
def at_eof(self):
|
|
520
|
+
''' Test whether the buffer is at end of input.
|
|
521
|
+
|
|
522
|
+
*Warning*: this will fetch from the `input_data` if the buffer
|
|
523
|
+
is empty and so it may block.
|
|
524
|
+
'''
|
|
525
|
+
if self.bufs:
|
|
526
|
+
return False
|
|
527
|
+
self.extend(1, short_ok=True)
|
|
528
|
+
return len(self) == 0
|
|
529
|
+
|
|
530
|
+
def report_offset(self, offset):
|
|
531
|
+
''' Report a pertinent offset.
|
|
532
|
+
'''
|
|
533
|
+
copy_offsets = self.copy_offsets
|
|
534
|
+
if copy_offsets is not None:
|
|
535
|
+
copy_offsets(offset)
|
|
536
|
+
|
|
537
|
+
def hint(self, size):
|
|
538
|
+
''' Hint that the caller is seeking at least `size` bytes.
|
|
539
|
+
|
|
540
|
+
If the `input_data` iterator has a `hint` method, this is
|
|
541
|
+
passed to it.
|
|
542
|
+
'''
|
|
543
|
+
try:
|
|
544
|
+
self.input_data.hint(size)
|
|
545
|
+
except AttributeError:
|
|
546
|
+
pass
|
|
547
|
+
|
|
548
|
+
def extend(self, min_size, short_ok=False):
|
|
549
|
+
''' Extend the buffer to at least `min_size` bytes.
|
|
550
|
+
|
|
551
|
+
If `min_size` is `Ellipsis`, extend the buffer to consume all the input.
|
|
552
|
+
This should really only be used with bounded buffers
|
|
553
|
+
in order to avoid unconstrained memory consumption.
|
|
554
|
+
|
|
555
|
+
If there are insufficient data available then an `EOFError`
|
|
556
|
+
will be raised unless `short_ok` is true (default `False`)
|
|
557
|
+
in which case the updated buffer will be short.
|
|
558
|
+
'''
|
|
559
|
+
if min_size is Ellipsis:
|
|
560
|
+
pass
|
|
561
|
+
elif min_size < 1:
|
|
562
|
+
raise ValueError("min_size(%r) must be >= 1" % (min_size,))
|
|
563
|
+
while min_size is Ellipsis or min_size > self.buflen:
|
|
564
|
+
if min_size is not Ellipsis:
|
|
565
|
+
self.hint(min_size - self.buflen)
|
|
566
|
+
try:
|
|
567
|
+
next_chunk = next(self.input_data)
|
|
568
|
+
except StopIteration:
|
|
569
|
+
if min_size is Ellipsis or short_ok:
|
|
570
|
+
return
|
|
571
|
+
# pylint: disable=raise-missing-from
|
|
572
|
+
raise EOFError(
|
|
573
|
+
"insufficient input data, wanted %d bytes but only found %d" %
|
|
574
|
+
(min_size, self.buflen)
|
|
575
|
+
)
|
|
576
|
+
else:
|
|
577
|
+
if self.progress is not None:
|
|
578
|
+
self.progress += len(next_chunk)
|
|
579
|
+
if next_chunk:
|
|
580
|
+
self.bufs.append(next_chunk)
|
|
581
|
+
self.buflen += len(next_chunk)
|
|
582
|
+
##assert self.buflen >= min_size
|
|
583
|
+
##assert self.buflen == sum(len(buf) for buf in self.bufs)
|
|
584
|
+
|
|
585
|
+
def tail_extend(self, size):
|
|
586
|
+
''' Extend method for parsers reading "tail"-like chunk streams,
|
|
587
|
+
typically raw reads from a growing file.
|
|
588
|
+
|
|
589
|
+
This may read 0 bytes at EOF, but a future read may read
|
|
590
|
+
more bytes if the file grows.
|
|
591
|
+
Such an iterator can be obtained from
|
|
592
|
+
``cs.fileutils.read_from(..,tail_mode=True)``.
|
|
593
|
+
'''
|
|
594
|
+
while size < len(self):
|
|
595
|
+
self.extend(size, short_ok=True)
|
|
596
|
+
|
|
597
|
+
def takev(self, size, short_ok=False):
|
|
598
|
+
''' Return the next `size` bytes as a list of chunks
|
|
599
|
+
(because the internal buffering is also a list of chunks).
|
|
600
|
+
Other arguments are as for extend().
|
|
601
|
+
|
|
602
|
+
See `.take()` to get a flat chunk instead of a list.
|
|
603
|
+
'''
|
|
604
|
+
if size == 0:
|
|
605
|
+
return []
|
|
606
|
+
if size is Ellipsis or size > self.buflen:
|
|
607
|
+
# extend the buffered data
|
|
608
|
+
self.extend(size, short_ok=short_ok)
|
|
609
|
+
# post: the buffer is as big as it is going to get for this call
|
|
610
|
+
if size is Ellipsis:
|
|
611
|
+
# take all the fetched data
|
|
612
|
+
taken = self.bufs
|
|
613
|
+
self.bufs = []
|
|
614
|
+
else:
|
|
615
|
+
if size >= self.buflen:
|
|
616
|
+
# take the whole buffer
|
|
617
|
+
taken = self.bufs
|
|
618
|
+
self.bufs = []
|
|
619
|
+
else:
|
|
620
|
+
# size < self.buflen
|
|
621
|
+
# take the leading data from the buffer
|
|
622
|
+
taken = []
|
|
623
|
+
bufs = self.bufs
|
|
624
|
+
while size > 0:
|
|
625
|
+
buf0 = bufs[0]
|
|
626
|
+
if len(buf0) <= size:
|
|
627
|
+
buf = buf0
|
|
628
|
+
bufs.pop(0)
|
|
629
|
+
else:
|
|
630
|
+
# len(buf0) > size: crop from buf0
|
|
631
|
+
assert len(buf0) > size
|
|
632
|
+
buf = buf0[:size]
|
|
633
|
+
bufs[0] = buf0[size:]
|
|
634
|
+
taken.append(buf)
|
|
635
|
+
size -= len(buf)
|
|
636
|
+
# advance offset by the size of the taken data
|
|
637
|
+
taken_size = sum(len(buf) for buf in taken)
|
|
638
|
+
self.buflen -= taken_size
|
|
639
|
+
self.offset += taken_size
|
|
640
|
+
return taken
|
|
641
|
+
|
|
642
|
+
def take(self, size, short_ok=False):
|
|
643
|
+
''' Return the next `size` bytes.
|
|
644
|
+
Other arguments are as for `.extend()`.
|
|
645
|
+
|
|
646
|
+
This is a thin wrapper for the `.takev` method.
|
|
647
|
+
'''
|
|
648
|
+
taken = self.takev(size, short_ok=short_ok)
|
|
649
|
+
if not taken:
|
|
650
|
+
return b''
|
|
651
|
+
if len(taken) == 1:
|
|
652
|
+
return bytes(taken[0])
|
|
653
|
+
return b''.join(taken)
|
|
654
|
+
|
|
655
|
+
def readline(self):
|
|
656
|
+
''' Return a binary "line" from `self`, where a line is defined by
|
|
657
|
+
its ending `b'\n'` delimiter.
|
|
658
|
+
The final line from a buffer might not have a trailing newline;
|
|
659
|
+
`b''` is returned at EOF.
|
|
660
|
+
|
|
661
|
+
Example:
|
|
662
|
+
|
|
663
|
+
>>> bfr = CornuCopyBuffer([b'abc', b'def\nhij'])
|
|
664
|
+
>>> bfr.readline()
|
|
665
|
+
b'abcdef\n'
|
|
666
|
+
>>> bfr.readline()
|
|
667
|
+
b'hij'
|
|
668
|
+
>>> bfr.readline()
|
|
669
|
+
b''
|
|
670
|
+
>>> bfr.readline()
|
|
671
|
+
b''
|
|
672
|
+
'''
|
|
673
|
+
pending = []
|
|
674
|
+
for bs in self:
|
|
675
|
+
nlpos = bs.find(b'\n')
|
|
676
|
+
if nlpos >= 0:
|
|
677
|
+
pending.append(bs[:nlpos + 1])
|
|
678
|
+
self.push(bs[nlpos + 1:])
|
|
679
|
+
break
|
|
680
|
+
pending.append(bs)
|
|
681
|
+
return b''.join(pending)
|
|
682
|
+
|
|
683
|
+
def peek(self, size, short_ok=False):
|
|
684
|
+
''' Examine the leading bytes of the buffer without consuming them,
|
|
685
|
+
a `take` followed by a `push`.
|
|
686
|
+
Returns the bytes.
|
|
687
|
+
'''
|
|
688
|
+
bs = self.take(size, short_ok=short_ok)
|
|
689
|
+
self.push(bs)
|
|
690
|
+
return bs
|
|
691
|
+
|
|
692
|
+
def read(self, size, one_fetch=False):
|
|
693
|
+
''' Compatibility method to allow using the buffer like a file.
|
|
694
|
+
|
|
695
|
+
Parameters:
|
|
696
|
+
* `size`: the desired data size
|
|
697
|
+
* `one_fetch`: do a single data fetch, default `False`
|
|
698
|
+
|
|
699
|
+
In `one_fetch` mode the read behaves like a POSIX file read,
|
|
700
|
+
returning up to to `size` bytes from a single I/O operation.
|
|
701
|
+
'''
|
|
702
|
+
if size < 1:
|
|
703
|
+
raise ValueError("size < 1: %r" % (size,))
|
|
704
|
+
if size <= self.buflen:
|
|
705
|
+
return self.take(size)
|
|
706
|
+
# size > self.buflen
|
|
707
|
+
if not one_fetch:
|
|
708
|
+
self.extend(size, short_ok=True)
|
|
709
|
+
taken = self.takev(min(size, self.buflen))
|
|
710
|
+
size -= sum(len(buf) for buf in taken)
|
|
711
|
+
if size > 0:
|
|
712
|
+
# want more data
|
|
713
|
+
if one_fetch:
|
|
714
|
+
try:
|
|
715
|
+
buf = next(self)
|
|
716
|
+
except StopIteration:
|
|
717
|
+
pass
|
|
718
|
+
else:
|
|
719
|
+
if size < len(buf):
|
|
720
|
+
# push back the tail of the buffer
|
|
721
|
+
self.push(buf[size:])
|
|
722
|
+
buf = buf[:size]
|
|
723
|
+
taken.append(buf)
|
|
724
|
+
if not taken:
|
|
725
|
+
return b''
|
|
726
|
+
if len(taken) == 1:
|
|
727
|
+
return taken[0]
|
|
728
|
+
return b''.join(taken)
|
|
729
|
+
|
|
730
|
+
def read1(self, size):
|
|
731
|
+
''' Shorthand method for `self.read(size,one_fetch=True)`.
|
|
732
|
+
'''
|
|
733
|
+
return self.read(size, one_fetch=True)
|
|
734
|
+
|
|
735
|
+
def byte0(self):
|
|
736
|
+
''' Consume the leading byte and return it as an `int` (`0`..`255`).
|
|
737
|
+
'''
|
|
738
|
+
byte0, = self.take(1)
|
|
739
|
+
return byte0
|
|
740
|
+
|
|
741
|
+
def tell(self):
|
|
742
|
+
''' Compatibility method to allow using the buffer like a file.
|
|
743
|
+
'''
|
|
744
|
+
return self.offset
|
|
745
|
+
|
|
746
|
+
def seek(self, offset, whence=None, short_ok=False):
|
|
747
|
+
''' Compatibility method to allow using the buffer like a file.
|
|
748
|
+
This returns the resulting absolute offset.
|
|
749
|
+
|
|
750
|
+
Parameters are as for `io.seek` except as noted below:
|
|
751
|
+
* `whence`: (default `os.SEEK_SET`). This method only supports
|
|
752
|
+
`os.SEEK_SET` and `os.SEEK_CUR`, and does not support seeking to a
|
|
753
|
+
lower offset than the current buffer offset.
|
|
754
|
+
* `short_ok`: (default `False`). If true, the seek may not reach
|
|
755
|
+
the target if there are insufficent `input_data` - the
|
|
756
|
+
position will be the end of the `input_data`, and the
|
|
757
|
+
`input_data` will have been consumed; the caller must check
|
|
758
|
+
the returned offset to check that it is as expected. If
|
|
759
|
+
false, a `ValueError` will be raised; however, note that the
|
|
760
|
+
`input_data` will still have been consumed.
|
|
761
|
+
'''
|
|
762
|
+
if whence is None:
|
|
763
|
+
whence = SEEK_SET
|
|
764
|
+
elif whence == SEEK_SET:
|
|
765
|
+
pass
|
|
766
|
+
elif whence == SEEK_CUR:
|
|
767
|
+
offset += self.offset
|
|
768
|
+
else:
|
|
769
|
+
raise ValueError(
|
|
770
|
+
"seek: unsupported whence value %s, must be os.SEEK_SET or os.SEEK_CUR"
|
|
771
|
+
% (whence,)
|
|
772
|
+
)
|
|
773
|
+
if offset < self.offset:
|
|
774
|
+
raise ValueError(
|
|
775
|
+
"seek: target offset %s < buffer offset %s; may not seek backwards" %
|
|
776
|
+
(offset, self.offset)
|
|
777
|
+
)
|
|
778
|
+
if offset > self.offset:
|
|
779
|
+
self.skipto(offset, short_ok=short_ok)
|
|
780
|
+
return self.offset
|
|
781
|
+
|
|
782
|
+
def skipto(self, new_offset, copy_skip=None, short_ok=False):
|
|
783
|
+
''' Advance to position `new_offset`. Return the new offset.
|
|
784
|
+
|
|
785
|
+
Parameters:
|
|
786
|
+
* `new_offset`: the target offset.
|
|
787
|
+
* `copy_skip`: callable to receive skipped data.
|
|
788
|
+
* `short_ok`: default `False`; if true then skipto may return before
|
|
789
|
+
`new_offset` if there are insufficient `input_data`.
|
|
790
|
+
|
|
791
|
+
Return values:
|
|
792
|
+
* `buf`: the new state of `buf`
|
|
793
|
+
* `offset`: the final offset; this may be short if `short_ok`.
|
|
794
|
+
'''
|
|
795
|
+
offset = self.offset
|
|
796
|
+
if new_offset < offset:
|
|
797
|
+
raise ValueError(
|
|
798
|
+
"skipto: new_offset:%d < offset:%d" % (new_offset, offset)
|
|
799
|
+
)
|
|
800
|
+
return self.skip(
|
|
801
|
+
new_offset - offset, copy_skip=copy_skip, short_ok=short_ok
|
|
802
|
+
)
|
|
803
|
+
|
|
804
|
+
def skip(self, toskip, copy_skip=None, short_ok=False):
|
|
805
|
+
''' Advance position by `skip_to`. Return the new offset.
|
|
806
|
+
|
|
807
|
+
Parameters:
|
|
808
|
+
* `toskip`: the distance to advance
|
|
809
|
+
* `copy_skip`: callable to receive skipped data.
|
|
810
|
+
* `short_ok`: default `False`; if true then skip may return before
|
|
811
|
+
`skipto` bytes if there are insufficient `input_data`.
|
|
812
|
+
'''
|
|
813
|
+
# consume buffered bytes in buf before the new offset
|
|
814
|
+
bufskip = min(toskip, self.buflen)
|
|
815
|
+
if bufskip > 0:
|
|
816
|
+
for buf in self.takev(bufskip):
|
|
817
|
+
if copy_skip:
|
|
818
|
+
copy_skip(buf)
|
|
819
|
+
toskip -= len(buf)
|
|
820
|
+
assert toskip >= 0
|
|
821
|
+
if toskip == 0:
|
|
822
|
+
return
|
|
823
|
+
# check that we consumed all the buffered data
|
|
824
|
+
assert not self.bufs
|
|
825
|
+
assert self.buflen == 0
|
|
826
|
+
# advance the rest of the way
|
|
827
|
+
seekable = False if copy_skip else self.seekable
|
|
828
|
+
if seekable is None or seekable:
|
|
829
|
+
# should we do a seek?
|
|
830
|
+
try:
|
|
831
|
+
input_seek = self.input_data.seek
|
|
832
|
+
except AttributeError:
|
|
833
|
+
if seekable is not None:
|
|
834
|
+
print(
|
|
835
|
+
"%s.skip: warning: seekable=%r but no input_data.seek method,"
|
|
836
|
+
" resetting seekable to False" % (self, seekable),
|
|
837
|
+
file=sys.stderr
|
|
838
|
+
)
|
|
839
|
+
self.seekable = False
|
|
840
|
+
else:
|
|
841
|
+
# input_data has a seek method, try to use it
|
|
842
|
+
new_offset = self.offset + toskip
|
|
843
|
+
input_offset = new_offset + self.input_offset_displacement
|
|
844
|
+
try:
|
|
845
|
+
input_seek(input_offset)
|
|
846
|
+
except OSError as e:
|
|
847
|
+
print(
|
|
848
|
+
"%s.skip: warning: input_data.seek(%r):"
|
|
849
|
+
" %s, resetting self.seekable to False" %
|
|
850
|
+
(self, input_offset, e),
|
|
851
|
+
file=sys.stderr
|
|
852
|
+
)
|
|
853
|
+
self.seekable = False
|
|
854
|
+
else:
|
|
855
|
+
# successful seek, update offset and return
|
|
856
|
+
self.offset = new_offset
|
|
857
|
+
return
|
|
858
|
+
# no seek, consume sufficient chunks
|
|
859
|
+
self.hint(toskip)
|
|
860
|
+
for buf in self.takev(toskip, short_ok=short_ok):
|
|
861
|
+
toskip -= len(buf)
|
|
862
|
+
assert toskip == 0
|
|
863
|
+
|
|
864
|
+
@contextmanager
|
|
865
|
+
def subbuffer(self, end_offset):
|
|
866
|
+
''' Context manager wrapper for `.bounded`
|
|
867
|
+
which calls the `.flush` method automatically
|
|
868
|
+
on exiting the context.
|
|
869
|
+
|
|
870
|
+
Example:
|
|
871
|
+
|
|
872
|
+
# avoid buffer overrun
|
|
873
|
+
with bfr.subbuffer(bfr.offset+128) as subbfr:
|
|
874
|
+
id3v1 = ID3V1Frame.parse(subbfr)
|
|
875
|
+
# ensure the whole buffer was consumed
|
|
876
|
+
assert subbfr.at_eof()
|
|
877
|
+
'''
|
|
878
|
+
subbfr = self.bounded(end_offset)
|
|
879
|
+
try:
|
|
880
|
+
yield subbfr
|
|
881
|
+
finally:
|
|
882
|
+
subbfr.flush()
|
|
883
|
+
|
|
884
|
+
def bounded(self, end_offset):
|
|
885
|
+
''' Return a new `CornuCopyBuffer` operating on a bounded view
|
|
886
|
+
of this buffer.
|
|
887
|
+
|
|
888
|
+
This supports parsing of the buffer contents without risk
|
|
889
|
+
of consuming past a certain point, such as the known end
|
|
890
|
+
of a packet structure.
|
|
891
|
+
|
|
892
|
+
Parameters:
|
|
893
|
+
* `end_offset`: the ending offset of the new buffer.
|
|
894
|
+
Note that this is an absolute offset, not a length.
|
|
895
|
+
|
|
896
|
+
The new buffer starts with the same offset as `self` and
|
|
897
|
+
use of the new buffer affects `self`. After a flush both
|
|
898
|
+
buffers will again have the same offset and the data consumed
|
|
899
|
+
via the new buffer will also have been consumed from `self`.
|
|
900
|
+
|
|
901
|
+
Here is an example.
|
|
902
|
+
* Make a buffer `bfr` with 9 bytes of data in 3 chunks.
|
|
903
|
+
* Consume 2 bytes, advancing the offset to 2.
|
|
904
|
+
* Make a new bounded buffer `subbfr` extending to offset
|
|
905
|
+
5. Its inital offset is also 2.
|
|
906
|
+
* Iterate over it, yielding the remaining single byte chunk
|
|
907
|
+
from ``b'abc'`` and then the first 2 bytes of ``b'def'``.
|
|
908
|
+
The new buffer's offset is now 5.
|
|
909
|
+
* Try to take 2 more bytes from the new buffer - this fails.
|
|
910
|
+
* Flush the new buffer, synchronising with the original.
|
|
911
|
+
The original's offset is now also 5.
|
|
912
|
+
* Take 2 bytes from the original buffer, which succeeds.
|
|
913
|
+
|
|
914
|
+
Example:
|
|
915
|
+
|
|
916
|
+
>>> bfr = CornuCopyBuffer([b'abc', b'def', b'ghi'])
|
|
917
|
+
>>> bfr.offset
|
|
918
|
+
0
|
|
919
|
+
>>> bfr.take(2)
|
|
920
|
+
b'ab'
|
|
921
|
+
>>> bfr.offset
|
|
922
|
+
2
|
|
923
|
+
>>> subbfr = bfr.bounded(5)
|
|
924
|
+
>>> subbfr.offset
|
|
925
|
+
2
|
|
926
|
+
>>> for bs in subbfr:
|
|
927
|
+
... print(bs)
|
|
928
|
+
...
|
|
929
|
+
b'c'
|
|
930
|
+
b'de'
|
|
931
|
+
>>> subbfr.offset
|
|
932
|
+
5
|
|
933
|
+
>>> subbfr.take(2)
|
|
934
|
+
Traceback (most recent call last):
|
|
935
|
+
...
|
|
936
|
+
EOFError: insufficient input data, wanted 2 bytes but only found 0
|
|
937
|
+
>>> subbfr.flush()
|
|
938
|
+
>>> bfr.offset
|
|
939
|
+
5
|
|
940
|
+
>>> bfr.take(2)
|
|
941
|
+
b'fg'
|
|
942
|
+
|
|
943
|
+
*WARNING*: if the bounded buffer is not completely consumed
|
|
944
|
+
then it is critical to call the new `CornuCopyBuffer`'s `.flush`
|
|
945
|
+
method to push any unconsumed buffer back into this buffer.
|
|
946
|
+
Recommended practice is to always call `.flush` when finished
|
|
947
|
+
with the new buffer.
|
|
948
|
+
The `CornuCopyBuffer.subbuffer` method returns a context manager
|
|
949
|
+
which does this automatically.
|
|
950
|
+
|
|
951
|
+
Also, because the new buffer may buffer some of the unconsumed
|
|
952
|
+
data from this buffer, use of the original buffer should
|
|
953
|
+
be suspended.
|
|
954
|
+
'''
|
|
955
|
+
bfr2 = CornuCopyBuffer(
|
|
956
|
+
_BoundedBufferIterator(self, end_offset), offset=self.offset
|
|
957
|
+
)
|
|
958
|
+
|
|
959
|
+
def flush():
|
|
960
|
+
''' Flush the internal buffer of `bfr2` back into `self`'s
|
|
961
|
+
internal buffer, adjusting the latter's `.offset` accordingly.
|
|
962
|
+
'''
|
|
963
|
+
for buf in reversed(bfr2.bufs):
|
|
964
|
+
self.push(buf)
|
|
965
|
+
|
|
966
|
+
bfr2.flush = flush # pylint: disable=attribute-defined-outside-init
|
|
967
|
+
return bfr2
|
|
968
|
+
|
|
969
|
+
@classmethod
|
|
970
|
+
def promote(cls, obj):
|
|
971
|
+
''' Promote `obj` to a `CornuCopyBuffer`,
|
|
972
|
+
used by the @cs.deco.promote` decorator.
|
|
973
|
+
|
|
974
|
+
Promotes:
|
|
975
|
+
* `int`: assumed to be a file descriptor of a file open for binary read
|
|
976
|
+
* `str`: assumed to be a filesystem pathname
|
|
977
|
+
* `bytes` and `bytes`like objects: data
|
|
978
|
+
* has a `.read1` or `.read` method: assume a file open for binary read
|
|
979
|
+
* iterable: assumed to be an iterable of `bytes`like objects
|
|
980
|
+
'''
|
|
981
|
+
if isinstance(obj, cls):
|
|
982
|
+
return obj
|
|
983
|
+
if isinstance(obj, int):
|
|
984
|
+
obj = cls.from_fd(obj)
|
|
985
|
+
elif isinstance(obj, str):
|
|
986
|
+
obj = cls.from_filename(obj)
|
|
987
|
+
elif isinstance(obj, (bytes, bytearray, mmap.mmap, memoryview)):
|
|
988
|
+
obj = cls.from_bytes(obj)
|
|
989
|
+
elif hasattr(obj, 'read1') or hasattr(obj, 'read'):
|
|
990
|
+
obj = cls.from_file(obj)
|
|
991
|
+
try:
|
|
992
|
+
iter(obj)
|
|
993
|
+
except TypeError:
|
|
994
|
+
pass
|
|
995
|
+
else:
|
|
996
|
+
# assume this iterates byteslike objects
|
|
997
|
+
return cls(obj)
|
|
998
|
+
raise TypeError("%s.promote: cannot promote %s" % (cls, r(obj)))
|
|
999
|
+
|
|
1000
|
+
class _BoundedBufferIterator(object):
|
|
1001
|
+
''' An iterator over the data from a CornuCopyBuffer with an end
|
|
1002
|
+
offset bound.
|
|
1003
|
+
'''
|
|
1004
|
+
|
|
1005
|
+
def __init__(self, bfr, end_offset):
|
|
1006
|
+
if end_offset < bfr.offset:
|
|
1007
|
+
raise ValueError(
|
|
1008
|
+
"end_offset(%d) < bfr.offset(%d)" % (end_offset, bfr.offset)
|
|
1009
|
+
)
|
|
1010
|
+
self.bfr = bfr
|
|
1011
|
+
self.end_offset = end_offset
|
|
1012
|
+
|
|
1013
|
+
@property
|
|
1014
|
+
def offset(self):
|
|
1015
|
+
''' The current iterator offset.
|
|
1016
|
+
'''
|
|
1017
|
+
return self.bfr.offset
|
|
1018
|
+
|
|
1019
|
+
def __iter__(self):
|
|
1020
|
+
return self
|
|
1021
|
+
|
|
1022
|
+
def __next__(self):
|
|
1023
|
+
bfr = self.bfr
|
|
1024
|
+
limit = self.end_offset - bfr.offset
|
|
1025
|
+
if limit <= 0:
|
|
1026
|
+
if limit < 0:
|
|
1027
|
+
raise RuntimeError("limit:%d < 0" % (limit,))
|
|
1028
|
+
raise StopIteration("limit reached")
|
|
1029
|
+
# post: limit > 0
|
|
1030
|
+
buf = next(bfr)
|
|
1031
|
+
# post: bfr's internal buffer now empty, can be modified
|
|
1032
|
+
length = len(buf)
|
|
1033
|
+
if length <= limit:
|
|
1034
|
+
return buf
|
|
1035
|
+
# return just the head, pushing the tail back into bfr
|
|
1036
|
+
head = buf[:limit]
|
|
1037
|
+
bfr.push(buf[limit:])
|
|
1038
|
+
return head
|
|
1039
|
+
|
|
1040
|
+
next = __next__
|
|
1041
|
+
|
|
1042
|
+
def hint(self, size):
|
|
1043
|
+
''' Pass hints through to the underlying buffer.
|
|
1044
|
+
'''
|
|
1045
|
+
self.bfr.hint(size)
|
|
1046
|
+
|
|
1047
|
+
def seek(self, offset, whence=SEEK_SET):
|
|
1048
|
+
''' Do a seek on the underlying buffer, obeying the bounds.
|
|
1049
|
+
'''
|
|
1050
|
+
if whence == SEEK_SET:
|
|
1051
|
+
pass
|
|
1052
|
+
elif whence == SEEK_CUR:
|
|
1053
|
+
offset += self.bfr.offset
|
|
1054
|
+
elif whence == SEEK_END:
|
|
1055
|
+
offset += self.end_offset
|
|
1056
|
+
if not self.offset <= offset <= self.end_offset:
|
|
1057
|
+
raise ValueError(
|
|
1058
|
+
"invalid seek position(%d) < self.offset(%d) or > self.end_offset(%d)"
|
|
1059
|
+
% (offset, self.offset, self.end_offset)
|
|
1060
|
+
)
|
|
1061
|
+
return self.bfr.seek(offset, SEEK_SET)
|
|
1062
|
+
|
|
1063
|
+
class CopyingIterator(object):
|
|
1064
|
+
''' Wrapper for an iterator that copies every item retrieved to a callable.
|
|
1065
|
+
'''
|
|
1066
|
+
|
|
1067
|
+
def __init__(self, it, copy_to):
|
|
1068
|
+
''' Initialise with the iterator `it` and the callable `copy_to`.
|
|
1069
|
+
'''
|
|
1070
|
+
self.it = it
|
|
1071
|
+
self.copy_to = copy_to
|
|
1072
|
+
|
|
1073
|
+
def __iter__(self):
|
|
1074
|
+
return self
|
|
1075
|
+
|
|
1076
|
+
def __next__(self):
|
|
1077
|
+
item = next(self.it)
|
|
1078
|
+
self.copy_to(item)
|
|
1079
|
+
return item
|
|
1080
|
+
|
|
1081
|
+
def __getattr__(self, attr):
|
|
1082
|
+
# proxy other attributes from the base iterator
|
|
1083
|
+
return getattr(self.it, attr)
|
|
1084
|
+
|
|
1085
|
+
class _Iterator(object):
|
|
1086
|
+
''' A base class for iterators over seekable things.
|
|
1087
|
+
'''
|
|
1088
|
+
|
|
1089
|
+
def __init__(self, offset=0, readsize=None, align=False):
|
|
1090
|
+
''' Initialise the `SeekableIterator`.
|
|
1091
|
+
|
|
1092
|
+
Parameters:
|
|
1093
|
+
* `offset`: the initial logical offset, kept up to date by
|
|
1094
|
+
iteration; default 0.
|
|
1095
|
+
* `readsize`: a preferred read/fetch size for iterators
|
|
1096
|
+
where that may be meaningful; if omitted then `DEFAULT_READSIZE`
|
|
1097
|
+
will be stored
|
|
1098
|
+
* `align`: whther to align reads/fetches by default: an
|
|
1099
|
+
iterator may choose to align fetches with multiples of
|
|
1100
|
+
`readsize`, doing a short fetch to bring the `offset`
|
|
1101
|
+
into alignment; the default is False
|
|
1102
|
+
'''
|
|
1103
|
+
if readsize is None:
|
|
1104
|
+
readsize = DEFAULT_READSIZE
|
|
1105
|
+
elif readsize < 1:
|
|
1106
|
+
raise ValueError("readsize must be >=1, got: %r" % (readsize,))
|
|
1107
|
+
if offset < 0:
|
|
1108
|
+
raise ValueError("offset must be >=0, got: %r" % (offset,))
|
|
1109
|
+
self.offset = offset
|
|
1110
|
+
self.readsize = readsize
|
|
1111
|
+
self.align = align
|
|
1112
|
+
self.next_hint = None
|
|
1113
|
+
|
|
1114
|
+
def __del__(self):
|
|
1115
|
+
self.close()
|
|
1116
|
+
|
|
1117
|
+
def close(self):
|
|
1118
|
+
''' Close the iterator; required by subclasses.
|
|
1119
|
+
'''
|
|
1120
|
+
raise NotImplementedError("missing close method")
|
|
1121
|
+
|
|
1122
|
+
def _fetch(self, readsize):
|
|
1123
|
+
raise NotImplementedError("no _fetch method in class %s" % (type(self),))
|
|
1124
|
+
|
|
1125
|
+
def hint(self, size):
|
|
1126
|
+
''' Hint that the next iteration is involved in obtaining at
|
|
1127
|
+
least `size` bytes.
|
|
1128
|
+
|
|
1129
|
+
Some sources may take this into account when fetching their
|
|
1130
|
+
next data chunk. Users should keep in mind that the source
|
|
1131
|
+
may need to allocate at least this much memory if it chooses
|
|
1132
|
+
to satisfy the hint in full.
|
|
1133
|
+
'''
|
|
1134
|
+
self.next_hint = size
|
|
1135
|
+
|
|
1136
|
+
def __iter__(self):
|
|
1137
|
+
return self
|
|
1138
|
+
|
|
1139
|
+
def __next__(self):
|
|
1140
|
+
''' Obtain more data from the iterator, honouring readsize, align and hint.
|
|
1141
|
+
'''
|
|
1142
|
+
readsize = self.readsize
|
|
1143
|
+
hint = self.next_hint
|
|
1144
|
+
if hint is None:
|
|
1145
|
+
if self.align:
|
|
1146
|
+
# trim the read to reach the next alignment point
|
|
1147
|
+
readsize -= self.offset % self.readsize
|
|
1148
|
+
else:
|
|
1149
|
+
# pad the read to the size of the hint
|
|
1150
|
+
readsize = max(readsize, hint)
|
|
1151
|
+
data = self._fetch(readsize)
|
|
1152
|
+
if not data:
|
|
1153
|
+
raise StopIteration("EOF, empty data received from fetch/read")
|
|
1154
|
+
length = len(data)
|
|
1155
|
+
self.offset += length
|
|
1156
|
+
if hint is not None:
|
|
1157
|
+
if hint > length:
|
|
1158
|
+
# trim the hint down
|
|
1159
|
+
hint -= length
|
|
1160
|
+
else:
|
|
1161
|
+
# hint consumed, clear it
|
|
1162
|
+
hint = None
|
|
1163
|
+
self.next_hint = hint
|
|
1164
|
+
return data
|
|
1165
|
+
|
|
1166
|
+
# pylint: disable=too-few-public-methods
|
|
1167
|
+
class SeekableIteratorMixin(object):
|
|
1168
|
+
''' Mixin supplying a logical with a `seek` method.
|
|
1169
|
+
'''
|
|
1170
|
+
|
|
1171
|
+
def seek(self, new_offset, mode=SEEK_SET):
|
|
1172
|
+
''' Move the logical offset.
|
|
1173
|
+
'''
|
|
1174
|
+
if mode == SEEK_SET:
|
|
1175
|
+
pass
|
|
1176
|
+
elif mode == SEEK_CUR:
|
|
1177
|
+
new_offset += self.offset
|
|
1178
|
+
elif mode == SEEK_END:
|
|
1179
|
+
try:
|
|
1180
|
+
end_offset = self.end_offset
|
|
1181
|
+
except AttributeError as e:
|
|
1182
|
+
# pylint: disable=raise-missing-from
|
|
1183
|
+
raise ValueError("mode=SEEK_END unsupported: %s" % (e,))
|
|
1184
|
+
new_offset += end_offset
|
|
1185
|
+
else:
|
|
1186
|
+
raise ValueError("unknown mode %d" % (mode,))
|
|
1187
|
+
self.offset = new_offset
|
|
1188
|
+
return new_offset
|
|
1189
|
+
|
|
1190
|
+
class FDIterator(_Iterator):
|
|
1191
|
+
''' An iterator over the data of a file descriptor.
|
|
1192
|
+
|
|
1193
|
+
*Note*: the iterator works with an os.dup() of the file
|
|
1194
|
+
descriptor so that it can close it with impunity; this requires
|
|
1195
|
+
the caller to close their descriptor.
|
|
1196
|
+
'''
|
|
1197
|
+
|
|
1198
|
+
def __init__(self, fd, offset=None, readsize=None, align=True):
|
|
1199
|
+
''' Initialise the iterator.
|
|
1200
|
+
|
|
1201
|
+
Parameters:
|
|
1202
|
+
* `fd`: file descriptor
|
|
1203
|
+
* `offset`: the initial logical offset, kept up to date by
|
|
1204
|
+
iteration; the default is the current file position.
|
|
1205
|
+
* `readsize`: a preferred read size; if omitted then
|
|
1206
|
+
`DEFAULT_READSIZE` will be stored
|
|
1207
|
+
* `align`: whether to align reads by default: if true then
|
|
1208
|
+
the iterator will do a short read to bring the `offset`
|
|
1209
|
+
into alignment with `readsize`; the default is `True`
|
|
1210
|
+
'''
|
|
1211
|
+
if offset is None:
|
|
1212
|
+
offset = 0
|
|
1213
|
+
_Iterator.__init__(self, offset=offset, readsize=readsize, align=align)
|
|
1214
|
+
# dup the fd so that we can close it with impunity
|
|
1215
|
+
self.fd = os.dup(fd)
|
|
1216
|
+
|
|
1217
|
+
def close(self):
|
|
1218
|
+
''' Close the file descriptor.
|
|
1219
|
+
'''
|
|
1220
|
+
if self.fd is not None:
|
|
1221
|
+
os.close(self.fd)
|
|
1222
|
+
self.fd = None
|
|
1223
|
+
|
|
1224
|
+
__del__ = close
|
|
1225
|
+
|
|
1226
|
+
def _fetch(self, readsize):
|
|
1227
|
+
return os.read(self.fd, readsize)
|
|
1228
|
+
|
|
1229
|
+
class SeekableFDIterator(FDIterator, SeekableIteratorMixin):
|
|
1230
|
+
''' An iterator over the data of a seekable file descriptor.
|
|
1231
|
+
|
|
1232
|
+
*Note*: the iterator works with an `os.dup()` of the file
|
|
1233
|
+
descriptor so that it can close it with impunity; this requires
|
|
1234
|
+
the caller to close their descriptor.
|
|
1235
|
+
'''
|
|
1236
|
+
|
|
1237
|
+
def __init__(self, fd, offset=None, **kw):
|
|
1238
|
+
if offset is None:
|
|
1239
|
+
offset = os.lseek(fd, 0, SEEK_CUR)
|
|
1240
|
+
FDIterator.__init__(self, fd, offset=offset, **kw)
|
|
1241
|
+
|
|
1242
|
+
def _fetch(self, readsize):
|
|
1243
|
+
return pread(self.fd, readsize, self.offset)
|
|
1244
|
+
|
|
1245
|
+
@property
|
|
1246
|
+
def end_offset(self):
|
|
1247
|
+
''' The end offset of the file.
|
|
1248
|
+
'''
|
|
1249
|
+
return os.fstat(self.fd).st_size
|
|
1250
|
+
|
|
1251
|
+
class FileIterator(_Iterator, SeekableIteratorMixin):
|
|
1252
|
+
''' An iterator over the data of a file object.
|
|
1253
|
+
|
|
1254
|
+
*Note*: the iterator closes the file on `__del__` or if its
|
|
1255
|
+
`.close` method is called.
|
|
1256
|
+
'''
|
|
1257
|
+
|
|
1258
|
+
def __init__(self, fp, offset=None, readsize=None, align=False):
|
|
1259
|
+
''' Initialise the iterator.
|
|
1260
|
+
|
|
1261
|
+
Parameters:
|
|
1262
|
+
* `fp`: file object
|
|
1263
|
+
* `offset`: the initial logical offset, kept up to date by
|
|
1264
|
+
iteration; the default is 0.
|
|
1265
|
+
* `readsize`: a preferred read size; if omitted then
|
|
1266
|
+
`DEFAULT_READSIZE` will be stored
|
|
1267
|
+
* `align`: whether to align reads by default: if true then
|
|
1268
|
+
the iterator will do a short read to bring the `offset`
|
|
1269
|
+
into alignment with `readsize`; the default is `False`
|
|
1270
|
+
'''
|
|
1271
|
+
if offset is None:
|
|
1272
|
+
offset = 0
|
|
1273
|
+
_Iterator.__init__(self, offset=offset, readsize=readsize, align=align)
|
|
1274
|
+
self.fp = fp
|
|
1275
|
+
# try to use the frugal read method if available
|
|
1276
|
+
try:
|
|
1277
|
+
read1 = fp.read1
|
|
1278
|
+
except AttributeError:
|
|
1279
|
+
read1 = fp.read
|
|
1280
|
+
self.read1 = read1
|
|
1281
|
+
|
|
1282
|
+
def close(self):
|
|
1283
|
+
''' Detach from the file. Does *not* call `fp.close()`.
|
|
1284
|
+
'''
|
|
1285
|
+
self.fp = None
|
|
1286
|
+
|
|
1287
|
+
def _fetch(self, readsize):
|
|
1288
|
+
return self.read1(readsize)
|
|
1289
|
+
|
|
1290
|
+
class SeekableFileIterator(FileIterator, SeekableIteratorMixin):
|
|
1291
|
+
''' An iterator over the data of a seekable file object.
|
|
1292
|
+
|
|
1293
|
+
*Note*: the iterator closes the file on __del__ or if its
|
|
1294
|
+
.close method is called.
|
|
1295
|
+
'''
|
|
1296
|
+
|
|
1297
|
+
def __init__(self, fp, offset=None, **kw):
|
|
1298
|
+
''' Initialise the iterator.
|
|
1299
|
+
|
|
1300
|
+
Parameters:
|
|
1301
|
+
* `fp`: file object
|
|
1302
|
+
* `offset`: the initial logical offset, kept up to date by
|
|
1303
|
+
iteration; the default is the current file position.
|
|
1304
|
+
* `readsize`: a preferred read size; if omitted then
|
|
1305
|
+
`DEFAULT_READSIZE` will be stored
|
|
1306
|
+
* `align`: whether to align reads by default: if true then
|
|
1307
|
+
the iterator will do a short read to bring the `offset`
|
|
1308
|
+
into alignment with `readsize`; the default is `False`
|
|
1309
|
+
'''
|
|
1310
|
+
if offset is None:
|
|
1311
|
+
offset = fp.tell()
|
|
1312
|
+
FileIterator.__init__(self, fp=fp, offset=offset, **kw)
|
|
1313
|
+
|
|
1314
|
+
def seek(self, new_offset, mode=SEEK_SET):
|
|
1315
|
+
''' Move the logical file pointer.
|
|
1316
|
+
|
|
1317
|
+
WARNING: moves the underlying file's pointer.
|
|
1318
|
+
'''
|
|
1319
|
+
new_offset = self.fp.seek(new_offset, mode)
|
|
1320
|
+
return super().seek(new_offset, SEEK_SET)
|
|
1321
|
+
|
|
1322
|
+
class SeekableMMapIterator(_Iterator, SeekableIteratorMixin):
|
|
1323
|
+
''' An iterator over the data of a mappable file descriptor.
|
|
1324
|
+
|
|
1325
|
+
*Note*: the iterator works with an `mmap` of an `os.dup()` of the
|
|
1326
|
+
file descriptor so that it can close it with impunity; this
|
|
1327
|
+
requires the caller to close their descriptor.
|
|
1328
|
+
'''
|
|
1329
|
+
|
|
1330
|
+
def __init__(self, fd, offset=None, readsize=None, align=True):
|
|
1331
|
+
''' Initialise the iterator.
|
|
1332
|
+
|
|
1333
|
+
Parameters:
|
|
1334
|
+
* `offset`: the initial logical offset, kept up to date by
|
|
1335
|
+
iteration; the default is the current file position.
|
|
1336
|
+
* `readsize`: a preferred read size; if omitted then
|
|
1337
|
+
`DEFAULT_READSIZE` will be stored
|
|
1338
|
+
* `align`: whether to align reads by default: if true then
|
|
1339
|
+
the iterator will do a short read to bring the `offset`
|
|
1340
|
+
into alignment with `readsize`; the default is `True`
|
|
1341
|
+
'''
|
|
1342
|
+
if offset is None:
|
|
1343
|
+
offset = os.lseek(fd, 0, SEEK_CUR)
|
|
1344
|
+
_Iterator.__init__(self, offset=offset, readsize=readsize, align=align)
|
|
1345
|
+
self.fd = os.dup(fd)
|
|
1346
|
+
self.base_offset = 0
|
|
1347
|
+
self.mmap = mmap.mmap(
|
|
1348
|
+
self.fd, 0, flags=mmap.MAP_PRIVATE, prot=mmap.PROT_READ
|
|
1349
|
+
)
|
|
1350
|
+
self.mv = memoryview(self.mmap)
|
|
1351
|
+
|
|
1352
|
+
def close(self):
|
|
1353
|
+
''' Detach from the file descriptor and mmap and close.
|
|
1354
|
+
'''
|
|
1355
|
+
if self.fd is not None:
|
|
1356
|
+
try:
|
|
1357
|
+
self.mmap.close()
|
|
1358
|
+
except BufferError:
|
|
1359
|
+
pass
|
|
1360
|
+
else:
|
|
1361
|
+
self.mmap = None
|
|
1362
|
+
os.close(self.fd)
|
|
1363
|
+
self.fd = None
|
|
1364
|
+
|
|
1365
|
+
@property
|
|
1366
|
+
def end_offset(self):
|
|
1367
|
+
''' The end offset of the mmap memoryview.
|
|
1368
|
+
'''
|
|
1369
|
+
return self.base_offset + len(self.mv)
|
|
1370
|
+
|
|
1371
|
+
def _fetch(self, readsize):
|
|
1372
|
+
if readsize < 1:
|
|
1373
|
+
raise ValueError("readsize=%d" % (readsize,))
|
|
1374
|
+
return self.mv[self.offset:self.offset + readsize]
|