Skip to main content

rill_graph/
backend_factory.rs

1//! # BackendFactory — constructor registry for audio backends
2
3use std::collections::HashMap;
4
5use rill_core::io::IoBackend;
6use rill_core::traits::ParamValue;
7
8/// Constructor signature.
9///
10/// Backend constructors receive a parameter map with string keys and
11/// [`ParamValue`] entries. Typical keys: `"sample_rate"`, `"buffer_size"`,
12/// `"channels"`. Each constructor parses the values it needs.
13pub type BackendCtor<T> =
14    fn(params: &HashMap<String, ParamValue>) -> Result<Box<dyn IoBackend<T>>, String>;
15
16/// Registry of named backend constructors (analogue of `NodeFactory`).
17pub struct BackendFactory<T> {
18    ctors: HashMap<&'static str, BackendCtor<T>>,
19}
20
21impl<T> BackendFactory<T> {
22    /// Create an empty backend factory.
23    pub fn new() -> Self {
24        Self {
25            ctors: HashMap::new(),
26        }
27    }
28
29    /// Register a named backend constructor.
30    pub fn register(&mut self, name: &'static str, ctor: BackendCtor<T>) {
31        self.ctors.insert(name, ctor);
32    }
33
34    /// Create a backend by name with the given parameters.
35    pub fn create(
36        &self,
37        name: &str,
38        params: &HashMap<String, ParamValue>,
39    ) -> Result<Box<dyn IoBackend<T>>, String> {
40        match self.ctors.get(name) {
41            Some(ctor) => ctor(params),
42            None => Err(format!("unknown backend: {name}")),
43        }
44    }
45
46    /// Returns `true` if a backend with the given name is registered.
47    pub fn contains(&self, name: &str) -> bool {
48        self.ctors.contains_key(name)
49    }
50}
51
52impl<T> Default for BackendFactory<T> {
53    fn default() -> Self {
54        Self::new()
55    }
56}