#Type Erasure?

1 messages · Page 1 of 1 (latest)

humble eagle
#

So I've never really worked with type erasure, but the term seems fitting for what I did right here. The whole purpose of this is to allow my to use a dyn TypeErasedCommandHandler.

Is this code considered alright? Is there a better way to do this?

Is this even considered "type erasure" or am I confusing this term here?

pub trait TakeableCommandHandler: Sync + Send {
   type Dispatcher: CommandDispatcher;

   fn key(&self) -> &'static str {
       Self::Dispatcher::key()
   }

   fn handle(&self, session: &mut Option<Session>) -> impl Future<Output = Result<()>> + Send;
}
#[async_trait]
pub trait TypeErasedCommandHandler: Send + Sync {
   fn key(&self) -> &'static str;

   async fn handle(&self, session: &mut Option<Session>) -> Result<()>;
}

#[async_trait]
impl<T> TypeErasedCommandHandler for T
where
   T: TakeableCommandHandler,
{
   fn key(&self) -> &'static str {
       self.key()
   }

   async fn handle(&self, session: &mut Option<Session>) -> Result<()> {
       self.handle(session).await
   }
}
pub struct HandlerCollection {
    commands: Arc<RwLock<HashMap<String, Arc<dyn TypeErasedCommandHandler>>>>,
}
astral forum
#

I could be wrong but I don’t think what you are doing here is type erasure, I think you’re just making use of dynamic trait objects

#

The form of type erasure that I am familiar with usually involves unsafe and some form of pointer casting

winter hazel
humble eagle
#

This is all mostly experimentation. I‘m trying to add Permissions to my RPC system, but my attempts so far have been mostly unsuccessful.

Either the solution is to clunky to use or it won‘t work at all.

I just stumbled upon this by accident and thought it was interesting.