Now that the Read::chars
iterator has been officially deprecated, what is the the proper way to obtain an iterator over the chars coming from a Reader
like stdin without reading the entire stream into memory?
相关问题
- Share Arc between closures
- Function references: expected bound lifetime param
- Pattern matching on slices
- How can I iteratively call Sha256::digest, passing
- Destructure a vector into variables and give away
相关文章
- How can I convert a f64 to f32 and get the closest
- What is a good way of cleaning up after a unit tes
- How can I unpack (destructure) elements from a vec
- How to import macros in Rust?
- How to get struct field names in Rust? [duplicate]
- using stdin in pycharm [duplicate]
- Confusion between [T] and &[T]
- How do I initialize an opaque C struct when using
As a couple others have mentioned, it is possible to copy the deprecated implementation of
Read::chars
for use in your own code. Whether this is truly ideal or not will depend on your use-case--for me, this proved to be good enough for now although it is likely that my application will outgrow this approach in the near-future.To illustrate how this can be done, let's look at a concrete example:
The above code also requires
read_one_byte
andutf8_char_width
to be implemented. Those should look something like:Now we can use the
MyReader
implementation to produce an iterator ofchar
s over some reader, likeio::stdin::Stdin
:The limitations of this approach are discussed at length in the original issue thread. One particular concern worth pointing out however is that this iterator will not handle non-UTF-8 encoded streams correctly.
The corresponding issue for deprecation nicely sums up the problems with
Read::chars
and offers suggestions:Your own iterator
The most efficient solution in terms of number of I/O calls is to read everything into a giant buffer
String
and iterate over that:You can combine this with an answer from Is there an owned version of String::chars?:
We now have a function that returns an iterator of
char
s for any type that implementsRead
.Once you have this pattern, it's just a matter of deciding where to make the tradeoff of memory allocation vs I/O requests. Here's a similar idea that uses line-sized buffers: