Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement readinto() method

I would like to implement a class which inherits from RawIOBase. I'm struggling to implement the readinto method. Basically, I don't know how to alter the content of the bytearray object passed as a parameter.

I've tried following (naive) approach:

def readinto(self, b):
    data = self.read(len(b))
    b = data
    return len(data)

But this, as I suspect, will assign new bytearray object to local variable b and it does not change content of the original bytearray.

like image 215
Luke Avatar asked Aug 21 '17 20:08

Luke


People also ask

What does read () method do in Python?

Description Python file method read () reads at most size bytes from the file. If the read hits EOF before obtaining size bytes, then it reads only available bytes.

What is readall and readinto in Java?

The default implementation defers to readall () and readinto (). Read and return all the bytes from the stream until EOF, using multiple calls to the stream if necessary. Read bytes into a pre-allocated, writable bytes-like object b, and return the number of bytes read. For example, b might be a bytearray .

What happens if read () method hits EOF before obtaining size bytes?

If the read hits EOF before obtaining size bytes, then it reads only available bytes. size − This is the number of bytes to be read from the file. This method returns the bytes read in string. The following example shows the usage of read () method.

How do I implement a method in Java?

Implement required methods. On the menu, click Ctrl+I. Alternatively, you can right-click anywhere in the class file, then click Generate Alt+Insert, and select Implement methods. Select the methods to implement. If necessary, select the Copy JavaDoc checkbox to insert JavaDoc comments for the implemented interface or abstract class.


1 Answers

from the docs of RawIOBase.readinto:

Read bytes into a pre-allocated, writable bytes-like object b, and return the number of bytes read. If the object is in non-blocking mode and no bytes are available, None is returned.

its a bit confusing but you need to write into the bytes-like object b (not read)

Example Usage

import io

class MyIO(io.RawIOBase):
    def readinto(self, b):
        msg = b'hello'
        b[:len(msg)] = msg
        return len(msg)

i = MyIO()
buf = bytearray()
i.readinto(buf)
print(buf)

Take a look at CPython implementation of BytesIO.readinto. basically its does memcpy from the object's buffer to the function input buffer.

like image 136
ShmulikA Avatar answered Oct 18 '22 07:10

ShmulikA