I am doing some socket IO, and using a bytearray object as a buffer. I would like to receive data with an offset into this buffer using csock.recv_into as shown below in order to avoid creating intermediary string objects. Unfortunately, it seems bytearrays can't be used this way, and the code below doesn't work.
buf = bytearray(b" " * toread)
read = 0
while(toread):
nbytes = csock.recv_into(buf[read:],toread)
toread -= nbytes
read += nbytes
So instead I am using the code below, which does use a temporary string (and works)...
buf = bytearray(b" " * toread)
read = 0
while(toread):
tmp = csock.recv(toread)
nbytes = len(tmp)
buf[read:] = tmp
toread -= nbytes
read += nbytes
Is there a more elegant way to do this that doesn't require copying intermediate strings around?
Use a memoryview
to wrap your bytearray
:
buf = bytearray(toread)
view = memoryview(buf)
while toread:
nbytes = sock.recv_into(view, toread)
view = view[nbytes:] # slicing views is cheap
toread -= nbytes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With