Skip to main content

qrcode_core/
plugin.rs

1//! Explicit plugin registry and object-safe extension points.
2//!
3//! The registry is intentionally local state: callers create a
4//! [`PluginRegistry`], register plugins into it, and pass it to facade or
5//! application code. This keeps plugin behavior deterministic and avoids hidden
6//! global mutation.
7
8use crate::{Color, ModuleSource, ModuleStorage};
9use alloc::boxed::Box;
10use alloc::collections::BTreeMap;
11use alloc::string::String;
12use alloc::vec::Vec;
13use core::fmt;
14
15/// Error type used by object-safe plugin entry points.
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub enum PluginError {
18    /// A named renderer was not present in the registry.
19    RendererNotFound(String),
20
21    /// A named encoder was not present in the registry.
22    EncoderNotFound(String),
23
24    /// The plugin configuration was invalid.
25    InvalidConfig(String),
26
27    /// A module grid shape was invalid.
28    InvalidModuleGrid,
29
30    /// A renderer failed.
31    RenderFailed(String),
32
33    /// An encoder failed.
34    EncodeFailed(String),
35
36    /// A postprocessor failed.
37    PostProcessFailed(String),
38}
39
40impl fmt::Display for PluginError {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        match self {
43            Self::RendererNotFound(name) => write!(f, "renderer plugin not found: {name}"),
44            Self::EncoderNotFound(name) => write!(f, "encoder plugin not found: {name}"),
45            Self::InvalidConfig(message) => write!(f, "invalid plugin config: {message}"),
46            Self::InvalidModuleGrid => f.write_str("invalid module grid"),
47            Self::RenderFailed(message) => write!(f, "renderer plugin failed: {message}"),
48            Self::EncodeFailed(message) => write!(f, "encoder plugin failed: {message}"),
49            Self::PostProcessFailed(message) => write!(f, "postprocessor plugin failed: {message}"),
50        }
51    }
52}
53
54#[cfg(feature = "std")]
55impl std::error::Error for PluginError {}
56
57/// Runtime renderer configuration passed to renderer factories.
58#[derive(Clone, Debug, Default, PartialEq, Eq)]
59pub struct RenderConfig {
60    format: Option<String>,
61    options: BTreeMap<String, String>,
62}
63
64impl RenderConfig {
65    /// Creates an empty render configuration.
66    #[must_use]
67    pub const fn new() -> Self {
68        Self { format: None, options: BTreeMap::new() }
69    }
70
71    /// Sets the requested output format.
72    #[must_use]
73    pub fn with_format(mut self, format: impl Into<String>) -> Self {
74        self.format = Some(format.into());
75        self
76    }
77
78    /// Adds or replaces an arbitrary string option.
79    #[must_use]
80    pub fn with_option(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
81        self.options.insert(key.into(), value.into());
82        self
83    }
84
85    /// Returns the requested output format, if one was configured.
86    #[must_use]
87    pub fn format(&self) -> Option<&str> {
88        self.format.as_deref()
89    }
90
91    /// Returns a string option by key.
92    #[must_use]
93    pub fn option(&self, key: &str) -> Option<&str> {
94        self.options.get(key).map(String::as_str)
95    }
96}
97
98/// Runtime encoder configuration passed to encoder factories.
99#[derive(Clone, Debug, Default, PartialEq, Eq)]
100pub struct EncodeConfig {
101    options: BTreeMap<String, String>,
102}
103
104impl EncodeConfig {
105    /// Creates an empty encode configuration.
106    #[must_use]
107    pub const fn new() -> Self {
108        Self { options: BTreeMap::new() }
109    }
110
111    /// Adds or replaces an arbitrary string option.
112    #[must_use]
113    pub fn with_option(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
114        self.options.insert(key.into(), value.into());
115        self
116    }
117
118    /// Returns a string option by key.
119    #[must_use]
120    pub fn option(&self, key: &str) -> Option<&str> {
121        self.options.get(key).map(String::as_str)
122    }
123}
124
125/// Type-erased render output returned by dynamic renderers.
126#[derive(Clone, Debug, PartialEq, Eq)]
127pub enum RenderOutput {
128    /// Text output such as SVG, HTML, ANSI, or plain strings.
129    Text(String),
130
131    /// Binary output such as PNG, PDF, or other encoded bytes.
132    Bytes(Vec<u8>),
133
134    /// A module-grid output for plugins that transform but do not serialize.
135    Modules(ModuleGrid),
136}
137
138/// Type-erased encode output returned by dynamic encoders.
139#[derive(Clone, Debug, PartialEq, Eq)]
140pub enum EncodedOutput {
141    /// Encoded QR modules.
142    Modules(ModuleGrid),
143
144    /// Opaque encoded bytes.
145    Bytes(Vec<u8>),
146}
147
148/// Owned mutable module grid used by plugin postprocessors.
149#[derive(Clone, Debug, PartialEq, Eq)]
150pub struct ModuleGrid {
151    modules: Vec<Color>,
152    width: usize,
153    height: usize,
154}
155
156impl ModuleGrid {
157    /// Creates a module grid from row-major modules.
158    ///
159    /// # Errors
160    ///
161    /// Returns [`PluginError::InvalidModuleGrid`] when the dimensions are zero
162    /// or `modules.len() != width * height`.
163    pub fn new(modules: Vec<Color>, width: usize, height: usize) -> Result<Self, PluginError> {
164        let Some(expected_len) = width.checked_mul(height) else {
165            return Err(PluginError::InvalidModuleGrid);
166        };
167        if width == 0 || height == 0 || modules.len() != expected_len {
168            return Err(PluginError::InvalidModuleGrid);
169        }
170        Ok(Self { modules, width, height })
171    }
172
173    /// Returns the grid modules as a mutable row-major slice.
174    #[must_use]
175    pub fn modules_mut(&mut self) -> &mut [Color] {
176        &mut self.modules
177    }
178}
179
180impl ModuleStorage for ModuleGrid {
181    fn get(&self, x: usize, y: usize) -> Color {
182        self.modules[y * self.width + x]
183    }
184
185    fn set(&mut self, x: usize, y: usize, color: Color) {
186        self.modules[y * self.width + x] = color;
187    }
188
189    fn width(&self) -> usize {
190        self.width
191    }
192
193    fn height(&self) -> usize {
194        self.height
195    }
196
197    fn modules(&self) -> &[Color] {
198        &self.modules
199    }
200}
201
202/// Object-safe renderer used by [`RendererFactory`].
203pub trait DynRenderer {
204    /// Renders a module source.
205    ///
206    /// # Errors
207    ///
208    /// Returns [`PluginError`] when the renderer cannot produce output.
209    fn render(&self, code: &dyn ModuleSource) -> Result<RenderOutput, PluginError>;
210}
211
212/// Factory for object-safe renderers.
213pub trait RendererFactory {
214    /// Builds a renderer from `config`.
215    fn build(&self, config: &RenderConfig) -> Box<dyn DynRenderer>;
216
217    /// Validates a renderer configuration before building it.
218    ///
219    /// The default implementation accepts every configuration, preserving
220    /// compatibility with existing plugin factories. Factories with
221    /// renderer-specific options can override this hook so
222    /// [`PluginRegistry::build_renderer`] reports invalid input before a
223    /// renderer is constructed.
224    fn validate_config(&self, _config: &RenderConfig) -> Result<(), PluginError> {
225        Ok(())
226    }
227}
228
229/// Object-safe encoder used by [`EncoderFactory`].
230pub trait DynEncoder {
231    /// Encodes raw input.
232    ///
233    /// # Errors
234    ///
235    /// Returns [`PluginError`] when the encoder cannot produce output.
236    fn encode(&self, input: &[u8]) -> Result<EncodedOutput, PluginError>;
237}
238
239/// Factory for object-safe encoders.
240pub trait EncoderFactory {
241    /// Builds an encoder from `config`.
242    fn build(&self, config: &EncodeConfig) -> Box<dyn DynEncoder>;
243}
244
245/// Object-safe postprocessor for in-place module-grid transforms.
246pub trait PostProcessor {
247    /// Processes `modules` in place.
248    ///
249    /// # Errors
250    ///
251    /// Returns [`PluginError`] when processing fails.
252    fn process(&self, modules: &mut dyn ModuleStorage) -> Result<(), PluginError>;
253}
254
255/// A plugin that registers one or more extension points.
256pub trait QrPlugin {
257    /// Stable plugin name.
258    fn name(&self) -> &str;
259
260    /// Plugin version string.
261    fn version(&self) -> &str;
262
263    /// Registers this plugin's extension points into `registry`.
264    fn register(&self, registry: &mut PluginRegistry);
265}
266
267/// Explicit plugin registry.
268#[derive(Default)]
269pub struct PluginRegistry {
270    plugins: BTreeMap<String, String>,
271    renderers: BTreeMap<String, Box<dyn RendererFactory>>,
272    encoders: BTreeMap<String, Box<dyn EncoderFactory>>,
273    postprocessors: Vec<Box<dyn PostProcessor>>,
274}
275
276impl PluginRegistry {
277    /// Creates an empty registry.
278    #[must_use]
279    pub const fn new() -> Self {
280        Self {
281            plugins: BTreeMap::new(),
282            renderers: BTreeMap::new(),
283            encoders: BTreeMap::new(),
284            postprocessors: Vec::new(),
285        }
286    }
287
288    /// Registers all extension points provided by `plugin`.
289    pub fn register_plugin<P: QrPlugin + ?Sized>(&mut self, plugin: &P) {
290        self.plugins.insert(String::from(plugin.name()), String::from(plugin.version()));
291        plugin.register(self);
292    }
293
294    /// Returns the registered version for a plugin name.
295    #[must_use]
296    pub fn plugin_version(&self, name: &str) -> Option<&str> {
297        self.plugins.get(name).map(String::as_str)
298    }
299
300    /// Iterates registered plugin names in deterministic order.
301    pub fn plugin_names(&self) -> impl Iterator<Item = &str> {
302        self.plugins.keys().map(String::as_str)
303    }
304
305    /// Registers or replaces a renderer factory by name.
306    pub fn register_renderer(
307        &mut self,
308        name: impl Into<String>,
309        factory: Box<dyn RendererFactory>,
310    ) -> Option<Box<dyn RendererFactory>> {
311        self.renderers.insert(name.into(), factory)
312    }
313
314    /// Registers or replaces an encoder factory by name.
315    pub fn register_encoder(
316        &mut self,
317        name: impl Into<String>,
318        factory: Box<dyn EncoderFactory>,
319    ) -> Option<Box<dyn EncoderFactory>> {
320        self.encoders.insert(name.into(), factory)
321    }
322
323    /// Appends a postprocessor to the registry.
324    pub fn register_postprocessor(&mut self, postprocessor: Box<dyn PostProcessor>) {
325        self.postprocessors.push(postprocessor);
326    }
327
328    /// Returns a renderer factory by name.
329    #[must_use]
330    pub fn renderer(&self, name: &str) -> Option<&dyn RendererFactory> {
331        self.renderers.get(name).map(Box::as_ref)
332    }
333
334    /// Builds a renderer by name.
335    ///
336    /// # Errors
337    ///
338    /// Returns [`PluginError::RendererNotFound`] when no renderer factory is
339    /// registered with `name`.
340    pub fn build_renderer(&self, name: &str, config: &RenderConfig) -> Result<Box<dyn DynRenderer>, PluginError> {
341        let factory = self.renderer(name).ok_or_else(|| PluginError::RendererNotFound(String::from(name)))?;
342        factory.validate_config(config)?;
343        Ok(factory.build(config))
344    }
345
346    /// Returns an encoder factory by name.
347    #[must_use]
348    pub fn encoder(&self, name: &str) -> Option<&dyn EncoderFactory> {
349        self.encoders.get(name).map(Box::as_ref)
350    }
351
352    /// Builds an encoder by name.
353    ///
354    /// # Errors
355    ///
356    /// Returns [`PluginError::EncoderNotFound`] when no encoder factory is
357    /// registered with `name`.
358    pub fn build_encoder(&self, name: &str, config: &EncodeConfig) -> Result<Box<dyn DynEncoder>, PluginError> {
359        let factory = self.encoder(name).ok_or_else(|| PluginError::EncoderNotFound(String::from(name)))?;
360        Ok(factory.build(config))
361    }
362
363    /// Returns all postprocessors in registration order.
364    #[must_use]
365    pub fn postprocessors(&self) -> &[Box<dyn PostProcessor>] {
366        &self.postprocessors
367    }
368
369    /// Applies all registered postprocessors in registration order.
370    ///
371    /// # Errors
372    ///
373    /// Returns the first [`PluginError`] reported by a postprocessor.
374    pub fn process_modules(&self, modules: &mut dyn ModuleStorage) -> Result<(), PluginError> {
375        for postprocessor in &self.postprocessors {
376            postprocessor.process(modules)?;
377        }
378        Ok(())
379    }
380
381    /// Iterates renderer names in deterministic order.
382    pub fn renderer_names(&self) -> impl Iterator<Item = &str> {
383        self.renderers.keys().map(String::as_str)
384    }
385
386    /// Iterates encoder names in deterministic order.
387    pub fn encoder_names(&self) -> impl Iterator<Item = &str> {
388        self.encoders.keys().map(String::as_str)
389    }
390}
391
392#[cfg(test)]
393mod tests {
394    use super::{
395        DynEncoder, DynRenderer, EncodeConfig, EncodedOutput, EncoderFactory, ModuleGrid, PluginRegistry,
396        PostProcessor, QrPlugin, RenderConfig, RenderOutput, RendererFactory,
397    };
398    use crate::{Color, ModuleSource, ModuleStorage};
399    use alloc::boxed::Box;
400    use alloc::string::ToString;
401
402    struct TextRenderer {
403        dark: char,
404    }
405
406    impl DynRenderer for TextRenderer {
407        fn render(&self, code: &dyn ModuleSource) -> Result<RenderOutput, super::PluginError> {
408            let mut out = String::new();
409            for y in 0..code.height() {
410                for x in 0..code.width() {
411                    out.push(if code.get(x, y) == Color::Dark { self.dark } else { '.' });
412                }
413            }
414            Ok(RenderOutput::Text(out))
415        }
416    }
417
418    struct TextRendererFactory;
419
420    impl RendererFactory for TextRendererFactory {
421        fn build(&self, config: &RenderConfig) -> Box<dyn DynRenderer> {
422            let dark = config.option("dark").and_then(|s| s.chars().next()).unwrap_or('#');
423            Box::new(TextRenderer { dark })
424        }
425    }
426
427    struct LengthEncoder;
428
429    impl DynEncoder for LengthEncoder {
430        fn encode(&self, input: &[u8]) -> Result<EncodedOutput, super::PluginError> {
431            Ok(EncodedOutput::Bytes(input.len().to_string().into_bytes()))
432        }
433    }
434
435    struct LengthEncoderFactory;
436
437    impl EncoderFactory for LengthEncoderFactory {
438        fn build(&self, _config: &EncodeConfig) -> Box<dyn DynEncoder> {
439            Box::new(LengthEncoder)
440        }
441    }
442
443    struct FlipFirst;
444
445    impl PostProcessor for FlipFirst {
446        fn process(&self, modules: &mut dyn ModuleStorage) -> Result<(), super::PluginError> {
447            modules.set(0, 0, Color::Dark);
448            Ok(())
449        }
450    }
451
452    struct FailPostprocessor;
453
454    impl PostProcessor for FailPostprocessor {
455        fn process(&self, _modules: &mut dyn ModuleStorage) -> Result<(), super::PluginError> {
456            Err(super::PluginError::PostProcessFailed("boom".into()))
457        }
458    }
459
460    struct DemoPlugin;
461
462    impl QrPlugin for DemoPlugin {
463        fn name(&self) -> &str {
464            "demo"
465        }
466
467        fn version(&self) -> &str {
468            "0.1.0"
469        }
470
471        fn register(&self, registry: &mut PluginRegistry) {
472            registry.register_renderer("text", Box::new(TextRendererFactory));
473            registry.register_encoder("length", Box::new(LengthEncoderFactory));
474            registry.register_postprocessor(Box::new(FlipFirst));
475        }
476    }
477
478    #[test]
479    fn registry_registers_and_uses_plugin_extension_points() {
480        let mut registry = PluginRegistry::new();
481        registry.register_plugin(&DemoPlugin);
482
483        let grid = ModuleGrid::new(alloc::vec![Color::Dark, Color::Light, Color::Light, Color::Dark], 2, 2).unwrap();
484        let config = RenderConfig::new().with_option("dark", "X");
485        let renderer = registry.build_renderer("text", &config).unwrap();
486        assert_eq!(renderer.render(&grid).unwrap(), RenderOutput::Text("X..X".into()));
487
488        let encoder = registry.build_encoder("length", &EncodeConfig::new()).unwrap();
489        assert_eq!(encoder.encode(b"abcd").unwrap(), EncodedOutput::Bytes(b"4".to_vec()));
490        assert_eq!(registry.plugin_version("demo"), Some("0.1.0"));
491        assert_eq!(registry.plugin_names().collect::<Vec<_>>(), ["demo"]);
492    }
493
494    #[test]
495    fn build_renderer_reports_missing_renderer_name() {
496        let registry = PluginRegistry::new();
497
498        assert!(matches!(
499            registry.build_renderer("missing", &RenderConfig::new()),
500            Err(super::PluginError::RendererNotFound(name)) if name == "missing"
501        ));
502    }
503
504    #[test]
505    fn build_encoder_reports_missing_encoder_name() {
506        let registry = PluginRegistry::new();
507
508        assert!(matches!(
509            registry.build_encoder("missing", &EncodeConfig::new()),
510            Err(super::PluginError::EncoderNotFound(name)) if name == "missing"
511        ));
512    }
513
514    #[test]
515    fn registry_keeps_names_deterministic() {
516        let mut registry = PluginRegistry::new();
517        registry.register_renderer("zeta", Box::new(TextRendererFactory));
518        registry.register_renderer("alpha", Box::new(TextRendererFactory));
519
520        let names = registry.renderer_names().collect::<Vec<_>>();
521        assert_eq!(names, ["alpha", "zeta"]);
522    }
523
524    #[test]
525    fn postprocessors_mutate_module_storage_in_order() {
526        let mut registry = PluginRegistry::new();
527        registry.register_postprocessor(Box::new(FlipFirst));
528        let mut grid = ModuleGrid::new(alloc::vec![Color::Light; 4], 2, 2).unwrap();
529
530        registry.process_modules(&mut grid).unwrap();
531
532        assert_eq!(ModuleSource::get(&grid, 0, 0), Color::Dark);
533    }
534
535    #[test]
536    fn process_modules_stops_on_first_postprocessor_error() {
537        let mut registry = PluginRegistry::new();
538        registry.register_postprocessor(Box::new(FailPostprocessor));
539        let mut grid = ModuleGrid::new(alloc::vec![Color::Light; 4], 2, 2).unwrap();
540
541        assert!(matches!(
542            registry.process_modules(&mut grid),
543            Err(super::PluginError::PostProcessFailed(message)) if message == "boom"
544        ));
545    }
546
547    #[test]
548    fn module_grid_rejects_dimension_multiplication_overflow() {
549        assert_eq!(ModuleGrid::new(alloc::vec![], usize::MAX, 2), Err(super::PluginError::InvalidModuleGrid));
550    }
551}