I need a completely in-memory object that I can give to BufReader
and BufWriter
. Something like Python's StringIO
. I want to write to and read from such an object using methods ordinarily used with File
s.
Is there a way to do this using the standard library?
If you want to use
BufReader
with an in-memoryString
, you can use theas_bytes()
method:This prints
read_buff got Potato!
. There is no need to use a cursor for this case.To use an in-memory
String
withBufWriter
, you can use theas_mut_vec
method. Unfortunately it isunsafe
and I have not found any other way. I don't like theCursor
approach since it consumes the vector and I have not found a way yet to use theCursor
together withBufWriter
.You don't need a
Cursor
most of the time.BufReader
requires a value that implementsRead
:BufWriter
requires a value that implementsWrite
:If you view the implementors of
Read
you will findimpl<'a> Read for &'a [u8]
.If you view the implementors of
Write
, you will findimpl Write for Vec<u8>
.Writing to a
Vec
will always append to the end. We also take a slice to theVec
that we can update. Each read ofc
will advance the slice further and further until it is empty.The main differences from
Cursor
:In fact there is a way. Meet
Cursor<T>
!In the documentation you can see that there are the following impls:
From this you can see that you can use the type
Cursor<Vec<u8>>
just as an ordinary file, becauseRead
,Write
andSeek
are implemented for that type!Little example (Playground):
For a more useful example, check the documentation linked above.