Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using bytearray with socket.recv_into

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?

like image 942
cyann Avatar asked Apr 12 '13 02:04

cyann


1 Answers

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
like image 69
nneonneo Avatar answered Sep 16 '22 15:09

nneonneo