Getting IOBuffer data after close method is called


#1

Hi All.

I’ve been working with some code that writes data to an IOBuffer, calls the close, method on said buffer.

i = IOBuffer()
write(i, "Wooo look at meeeee!")
close(i)

Obv the above is a really dumb toy example, but this is basically the essence of my question:

I want the data of a closed IOBuffer. It must be a closed buffer. And I want to do it in the most efficient way possible.

I know the take! method is supposed to give you the data array, without copying, and so was a good candidate:

julia> i = IOBuffer()
IOBuffer(data=UInt8[...], readable=true, writable=true, seekable=true, append=false, size=0, maxsize=Inf, ptr=1, mark=-1)

julia> write(i, "Wooo look at meeeee!")
20

julia> close(i)

julia> take!(i)
ERROR: ArgumentError: read failed, IOBuffer is not readable

This is because the close method makes the IOBuffer not readable, writable, or appendable.

I can see two options:

A). Open a new buffer with the data:

i2 = IOBuffer(i.data)
take!(i2)

B). Just take the reference to the array already!

i.data

However I thought I would ask here what the preferred approach to doing this would be, since i.data is directly accessing an internal field and not calling some method which would be more robust to internal struct changes in the future, and actually so is doing IOBuffer(i.data) followed by a take!.


#2

close might be permitted to destroy the buffer, so it can’t give it back to you afterwards.

Perhaps you’re looking for BufferStream instead?