Add a read1 to ByteBuffer for reading an int

Bytes-like objects have some strangeness regarding slicing.  But if you provide
only a start, it gives you an int.  Any other conditions, it gives you a
bytes-like object.  That doesn't translate to our read method which may not be
slicable.  So we either need to make sure we always explicitly turn things into
an int when we need them with ord(), or this.

So, this.
This commit is contained in:
T. Joseph Carter 2017-07-19 14:06:41 -07:00
parent 48f65d6f55
commit 614842d12b
2 changed files with 32 additions and 3 deletions

View File

@ -86,6 +86,19 @@ class BufferType(metaclass=ABCMeta):
""" """
pass pass
@abstractmethod
def read1(
self,
offset: int = 0,
limit: bool = True
) -> int:
"""Return int of single byte from buffer at offset
Should raise IndexError if an attempt to read past the end of the
buffer is made.
"""
pass
def write( def write(
self, self,
buf: bytes, buf: bytes,

View File

@ -55,7 +55,7 @@ class ByteBuffer(BufferType):
return trncated or empty results as with python slicing return trncated or empty results as with python slicing
""" """
if count is None: if count is None:
count = len(self) count = len(self) - start
try: try:
assert(start >= 0) assert(start >= 0)
assert(count >= 0) assert(count >= 0)
@ -63,8 +63,24 @@ class ByteBuffer(BufferType):
assert(start + count <= len(self._buf)) assert(start + count <= len(self._buf))
except AssertionError: except AssertionError:
raise IndexError('buffer read with index out of range') raise IndexError('buffer read with index out of range')
ret = self._buf[start:start + count] return bytes(self._buf[start:start + count])
return bytes(ret) if count != 1 else int(ret[0])
def read1(
self,
offset: int = 0,
limit: bool = True
) -> int:
"""Return int of single byte from buffer at offset
Should raise IndexError if an attempt to read past the end of the
buffer is made.
"""
try:
if limit == True:
assert 0 <= offset <= len(self._buf)
except AssertionError:
raise IndexError('buffer read with index out of range')
return self._buf[offset]
def write( def write(
self, self,