yjshen
yjshen

Reputation: 6693

How to define a registry which contains generic trait that implementations may be defined at runtime

I'm having trouble while designing a registry with generic types (playground):

use std::fs::File;
use std::collections::HashMap;

type Result<T> = std::result::Result<T, std::io::Error>;

// extern crate that enforce an associate type T 
trait Reader {
    type T;
    fn get_reader(&self) -> Result<Self::T>;
}

// my lib code below
trait ProtocolHandler<R> {
    fn get_reader(&self, path: &str) -> Result<Box<dyn Reader<T = R>>>;
}

struct LocalFSHandler {}

// Each Handler has fixed type for R, here File for LocalFSHandler
impl ProtocolHandler<File> for LocalFSHandler {
    fn get_reader(&self, path: &str) -> Result<Box<dyn Reader<T = File>>> {
        todo!()
    }
}

struct HandlerRegistry {
    // this doesn't compile since lacks of generic argument R
    handlers: HashMap<String, Box<dyn ProtocolHandler>>
}

impl HandlerRegistry {
    fn new() -> Self {
        let mut map: HashMap<String, Box<dyn ProtocolHandler>> = HashMap::new();
        map.insert("local", Box::new(LocalFSHandler {}));
        Self {
            handlers: map,
        }
    }
    
    fn get(&self, name: &str) -> Option<Box<dyn ProtocolHandler>> {
        self.handlers.get(name).cloned()
    }
}
// end of my lib code

// user code
fn main() {
    let registry = HandlerRegistry::new();
    // register one's own handler to registry, which is not known to my lib
    // therefore I cannot try cast by defining a Box<dyn Any> for hashmap value?
    
    // how can I made my lib handler implementation agnostic and cast to the
    // right one at runtime while getting out from the HashMap?
}

How should I adapt my code in order to get my registry itself implementation agnostic and might be populated by users at runtime?

I think I cannot define hashMap value as Box<dyn Any> since I cannot do cast to each possible handler type which is not known to my lib?

Upvotes: 0

Views: 295

Answers (1)

Elias Holzmann
Elias Holzmann

Reputation: 3669

You can't hold trait objects for different traits inside the same HashMap – that is also true if those different traits are just different variants of the same generic base trait.

In your case, you could hold std::any::Any and make sure that those objects are of some variant of ProtocolHandler<T> while handling insert() and get() (please note I added some inline comments):

use std::collections::HashMap;
use std::fs::File;

type Result<T> = std::result::Result<T, std::io::Error>;

trait Reader {
    type T;
    fn get_reader(&self) -> Result<Self::T>;
}

trait ProtocolHandler<R> {
    fn get_reader(&self, path: &str) -> Result<Box<dyn Reader<T = R>>>;
}

struct LocalFSHandler {}

impl ProtocolHandler<File> for LocalFSHandler {
    fn get_reader(&self, path: &str) -> Result<Box<dyn Reader<T = File>>> {
        todo!()
    }
}

struct SomeOtherHandler {}

impl ProtocolHandler<()> for SomeOtherHandler {
    fn get_reader(&self, path: &str) -> Result<Box<dyn Reader<T = ()>>> {
        todo!()
    }
}

struct HandlerRegistry {
    /* We can't only allow ProtocolHandler<R> for any R here. We could introduce
       a new trait that is held here and has a `impl<R> NewTrait for
       ProtocolHandler<R>`, but it is easier to just have Any in the HashMap and
       to check types vi bounds on our methods. 
    */
    handlers: HashMap<String, Box<dyn std::any::Any>>,
}

impl HandlerRegistry {
    fn new() -> Self {
        let map: HashMap<String, Box<dyn std::any::Any>> = HashMap::new();
        // switched the order of the next two statements to show HandlerRegistry::insert() in action
        let mut result = Self { handlers: map };
        result.insert("local", LocalFSHandler {});
        result
    }

    // both insert() and get() are generic for any ProtocolHandler type
    fn insert<T: 'static + ProtocolHandler<R>, R, K: Into<String>>(&mut self, key: K, value: T) {
        self.handlers.insert(key.into(), Box::new(value));
    }

    fn get<T: 'static + ProtocolHandler<R>, R>(&self, key: &str) -> Option<&T> {
        match self
            .handlers
            .get(key)
            .map(|obj| (**obj).downcast_ref::<T>())
        {
            Some(some) => some,
            None => None,
        }
    }
}

fn main() {
    let registry = HandlerRegistry::new();
    // If you now get "local" as a LocalFSHandler, this returns Some(LocalFSHandler)...
    assert!(registry.get::<LocalFSHandler, _>("local").is_some());
    // But if you try to get it as SomeOtherHandler, this returns None, because that's the wrong type
    assert!(registry.get::<SomeOtherHandler, _>("local").is_none());
}

Playground

Note that you are more or less opting out of strict typing here. You won't be able to notice typing problems at compile time, only at runtime. I don't know the context in which this will be used – if this is really what you want and need, go for it. Otherwise, I suggest to rethink the design. For example, if you know all types of R for which ProtocolHandler<R>s may exist, it might be better to hold an enum containing these possible ProtocolHandler variants instead of Any.

Upvotes: 1

Related Questions