tokio-rs / tokio

A runtime for writing reliable asynchronous applications with Rust. Provides I/O, networking, scheduling, timers, ...
https://tokio.rs
MIT License
27.16k stars 2.49k forks source link

Implement `StreamMap::get` to be able to obtain a reference to a specific stream #5131

Open j-a-m-l opened 2 years ago

j-a-m-l commented 2 years ago

Is your feature request related to a problem? Please describe. Currently is not possible to get a reference to a stream in StreamMap. I'd like to contribute to change that if you are OK with my approach.

Describe the solution you'd like Although I've not tried it yet, a possible implementation is:

    pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
    where
        K: Borrow<Q>,
        Q: Hash + Eq,
    {
        self.iter().find(|(k, _)| k == &key).map(|(_, value)| value)
    }

Describe alternatives you've considered The proposed solution mimics HashMap::get and it is similar to StreamMap::contains_key.

Additional context I'm using something like this in my project:

struct MyStreams {
  streams: StreamMap<String, MyStream>
}

impl Streams {
    pub fn get_stream(&self, key: &str) -> Option<&MyStream> {
        self.streams.iter().find(|(k, _)| k == &key).map(|(_, value)| value)
    }
}
Darksonn commented 2 years ago

I am reluctant to add this under the current implementation due to its running time, but a rewrite that uses a HashMap would make this easy to provide.

j-a-m-l commented 2 years ago

It is clearly stated in the documentation that «StreamMap works best with a “smallish” number of streams as all entries are scanned on insert, remove, and polling». So, this is something that it's not going to surprise any developer that uses it.

I understand your concern about the performance of the current implementation, but I'm not sure why adding this method could affect in any negative way the current implementation. I don't even think that it could constraint the future HashMap based implementation in any way.

My idea was creating a PR with that function, documentation and tests, maybe even implementing other similar functions in other PRs just for fun, but I doubt that I could dedicate time to rewrite the internals, with all the possible edge cases, etc. during the next months which, BTW, are quite busy for me already.

ivanrg99 commented 4 days ago

Any updates on this?