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