libzt
libzt copied to clipboard
python: Implement recv_into()
Implement recv_into() method in Python socket API
Useful for integrating libzt sockets anywhere that Python sockets are currently used.
Signature: def recv_into(self, buffer: bytes, n_bytes: int = 0, flags: int = 0) -> int
Expected behaviour: Read n_bytes
bytes into buffer
. If n_bytes
> len(buffer)
, raise an error. Return number of bytes actually read.
Example implementation (Python):
def recv_into(self, buffer: bytes, n_bytes: int = 0, flags: int = 0) -> int:
"""Receive `n_bytes` of data, writing into `buffer`
:param buffer: Byte buffer
:param n_bytes: (optional) Number of bytes to read (default: length of buffer)
:param flags: (optional) Flags
:return: Number of bytes read
"""
if n_bytes < 0:
raise ValueError("negative buffersize in recv_into")
n_bytes = n_bytes or len(buffer)
if len(buffer) < n_bytes:
raise ValueError("buffer too small for requested bytes")
if n_bytes > 0:
# TODO: This part should be replaced with a native library call
recv_bytes = self.recv(n_bytes, flags=flags)
buffer.join(recv_bytes)
return len(recv_bytes)
else:
return 0