You can’t write directly to the buffer of an IOBuffer, because the docs of IOBuffer states:
Passing
dataas scratch space toIOBufferwithwrite=truemay give unexpected behavior
Once write is called on an IOBuffer, it is best to consider any previous references to data invalidated; in effect IOBuffer “owns” this data until a call to take!. Any indirect mutations to data
could lead to undefined behavior by breaking the abstractions expected by IOBuffer.
You have two options:
- Carry around your own buffer, e.g. a
Vector{UInt8}, and then write your integers to that. Then flush that buffer to your IO when it’s reached a certain size. However, this is pretty annoying. What if you are writing a bunch of different stuff, interleaved, and just not integers? Why should you implement the flushing logic yourself? Etc. etc. - Just use
BufferIO.jl. For example:
using BufferIO
# use arbitrary IO sink, could be a file or whatever, here IOBuffer
io = BufWriter(IOBuffer())
@allocated write(io, 5) # returns zero