typed-openrpc 0.1.1

Typed JSON-RPC 2.0 method definitions with OpenRPC document generation.
Documentation
use crate::rpc_method::{MethodDoc, RpcMethod};

/// Collects all documented RPC methods.
#[derive(Clone, Debug, Default)]
pub struct Registry {
    methods: Vec<MethodDoc>,
}

impl Registry {
    /// Create an empty registry.
    pub fn new() -> Self {
        Self::default()
    }

    /// Return an iterator over registered methods.
    pub fn methods(&self) -> &[MethodDoc] {
        &self.methods
    }

    /// Consume the registry and yield the collected methods.
    pub fn into_methods(self) -> Vec<MethodDoc> {
        self.methods
    }

    /// Add an arbitrary method documentation entry.
    pub fn register(&mut self, doc: MethodDoc) {
        self.methods.push(doc);
    }

    /// Convenience wrapper for registering a `RpcMethod` implementation.
    pub fn register_method<M: RpcMethod>(&mut self) {
        self.register(MethodDoc::from::<M>());
    }

    /// Extend the registry with multiple method docs.
    pub fn extend<I>(&mut self, docs: I)
    where
        I: IntoIterator<Item = MethodDoc>,
    {
        self.methods.extend(docs);
    }

    #[cfg(feature = "inventory")]
    /// Populate the registry with methods submitted through the `inventory` crate.
    ///
    /// Typically this is used alongside the `#[rpc_method]` macro, which registers each method
    /// when the `inventory` feature is enabled. Calling `collect` (or
    /// [`registry_from_inventory`](crate::registry_from_inventory)) lets you gather these
    /// definitions at build or runtime to generate an OpenRPC document.
    pub fn collect(&mut self) {
        for entry in inventory::iter::<crate::MethodDocInventoryEntry> {
            self.register((entry.constructor)());
        }
    }
}

/// Entry submitted via the `inventory` registry.
#[cfg(feature = "inventory")]
pub struct MethodDocInventoryEntry {
    pub constructor: fn() -> MethodDoc,
}

#[cfg(feature = "inventory")]
inventory::collect!(MethodDocInventoryEntry);