简体   繁体   中英

How to check if a stream is empty at the current moment in time in Rust?

Suppose I have a type implementing Stream (I'm using async-tungstenite for context). Everything works (yay,). except my tests (boo! – I suppose that also means that not everything works).

I create a stream:

let (ws_stream_3, _) = connect_async(ws_addr).await.expect("Failed to connect");
let (mut write_3, mut read_3) = ws_stream_3.split();

Later on in the program I'd like to check that this stream has not had any messages sent to it. My first thought was:

assert!(read_3.next().await.is_none());

(it was a very brief thought – not for the program though, which runs forever like this - a good sign that no message is being received, but not very helpful for a unit test).

Is there a way to check if there are items in the stream right now (rather than waiting for the next one to arrive, which doesn't work because I want to make sure that it doesn't arrive).

I was able to fix this for this case by just using select! on that future (and a sleep of n seconds), but I think my intuitions are wrong here.

Is there a better way to do this?

You can call now_or_never on the next element, which will evaluate and consume the future immediately, rather than waiting for a result:

use futures::FutureExt;

assert!(read_3.next().now_or_never().is_none());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM