mirror of https://github.com/iKarith/cppo-ng.git
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:
parent
48f65d6f55
commit
614842d12b
|
@ -86,6 +86,19 @@ class BufferType(metaclass=ABCMeta):
|
|||
"""
|
||||
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(
|
||||
self,
|
||||
buf: bytes,
|
||||
|
|
|
@ -55,7 +55,7 @@ class ByteBuffer(BufferType):
|
|||
return trncated or empty results as with python slicing
|
||||
"""
|
||||
if count is None:
|
||||
count = len(self)
|
||||
count = len(self) - start
|
||||
try:
|
||||
assert(start >= 0)
|
||||
assert(count >= 0)
|
||||
|
@ -63,8 +63,24 @@ class ByteBuffer(BufferType):
|
|||
assert(start + count <= len(self._buf))
|
||||
except AssertionError:
|
||||
raise IndexError('buffer read with index out of range')
|
||||
ret = self._buf[start:start + count]
|
||||
return bytes(ret) if count != 1 else int(ret[0])
|
||||
return bytes(self._buf[start:start + count])
|
||||
|
||||
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(
|
||||
self,
|
||||
|
|
Loading…
Reference in New Issue