From 708665cebba8ef4b21c30cd71841b6309885347c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= Date: Mon, 5 Feb 2024 00:15:35 +0100 Subject: [PATCH] Use `TypeId` to identify `subscription::Map` --- futures/src/subscription.rs | 37 +++++++++++++++++++++++++++---------- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/futures/src/subscription.rs b/futures/src/subscription.rs index 7163248dc8..4d5a119293 100644 --- a/futures/src/subscription.rs +++ b/futures/src/subscription.rs @@ -10,6 +10,7 @@ use crate::{BoxStream, MaybeSend}; use futures::channel::mpsc; use futures::never::Never; +use std::any::TypeId; use std::hash::Hash; /// A stream of runtime events. @@ -88,7 +89,10 @@ impl Subscription { } /// Transforms the [`Subscription`] output with the given function. - pub fn map(mut self, f: fn(Message) -> A) -> Subscription + pub fn map( + mut self, + f: impl Fn(Message) -> A + MaybeSend + Clone + 'static, + ) -> Subscription where Message: 'static, A: 'static, @@ -97,8 +101,9 @@ impl Subscription { recipes: self .recipes .drain(..) - .map(|recipe| { - Box::new(Map::new(recipe, f)) as Box> + .map(move |recipe| { + Box::new(Map::new(recipe, f.clone())) + as Box> }) .collect(), } @@ -143,27 +148,39 @@ pub trait Recipe { fn stream(self: Box, input: EventStream) -> BoxStream; } -struct Map { +struct Map +where + F: Fn(A) -> B + 'static, +{ + id: TypeId, recipe: Box>, - mapper: fn(A) -> B, + mapper: F, } -impl Map { - fn new(recipe: Box>, mapper: fn(A) -> B) -> Self { - Map { recipe, mapper } +impl Map +where + F: Fn(A) -> B + 'static, +{ + fn new(recipe: Box>, mapper: F) -> Self { + Map { + id: TypeId::of::(), + recipe, + mapper, + } } } -impl Recipe for Map +impl Recipe for Map where A: 'static, B: 'static, + F: Fn(A) -> B + 'static + MaybeSend, { type Output = B; fn hash(&self, state: &mut Hasher) { + self.id.hash(state); self.recipe.hash(state); - self.mapper.hash(state); } fn stream(self: Box, input: EventStream) -> BoxStream {