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        if width == 0 || height == 0 || modules.len() != width * height {
165            return Err(PluginError::InvalidModuleGrid);
166        }
167        Ok(Self { modules, width, height })
168    }
169
170    /// Returns the grid modules as a mutable row-major slice.
171    #[must_use]
172    pub fn modules_mut(&mut self) -> &mut [Color] {
173        &mut self.modules
174    }
175}
176
177impl ModuleStorage for ModuleGrid {
178    fn get(&self, x: usize, y: usize) -> Color {
179        self.modules[y * self.width + x]
180    }
181
182    fn set(&mut self, x: usize, y: usize, color: Color) {
183        self.modules[y * self.width + x] = color;
184    }
185
186    fn width(&self) -> usize {
187        self.width
188    }
189
190    fn height(&self) -> usize {
191        self.height
192    }
193
194    fn modules(&self) -> &[Color] {
195        &self.modules
196    }
197}
198
199/// Object-safe renderer used by [`RendererFactory`].
200pub trait DynRenderer {
201    /// Renders a module source.
202    ///
203    /// # Errors
204    ///
205    /// Returns [`PluginError`] when the renderer cannot produce output.
206    fn render(&self, code: &dyn ModuleSource) -> Result<RenderOutput, PluginError>;
207}
208
209/// Factory for object-safe renderers.
210pub trait RendererFactory {
211    /// Builds a renderer from `config`.
212    fn build(&self, config: &RenderConfig) -> Box<dyn DynRenderer>;
213}
214
215/// Object-safe encoder used by [`EncoderFactory`].
216pub trait DynEncoder {
217    /// Encodes raw input.
218    ///
219    /// # Errors
220    ///
221    /// Returns [`PluginError`] when the encoder cannot produce output.
222    fn encode(&self, input: &[u8]) -> Result<EncodedOutput, PluginError>;
223}
224
225/// Factory for object-safe encoders.
226pub trait EncoderFactory {
227    /// Builds an encoder from `config`.
228    fn build(&self, config: &EncodeConfig) -> Box<dyn DynEncoder>;
229}
230
231/// Object-safe postprocessor for in-place module-grid transforms.
232pub trait PostProcessor {
233    /// Processes `modules` in place.
234    ///
235    /// # Errors
236    ///
237    /// Returns [`PluginError`] when processing fails.
238    fn process(&self, modules: &mut dyn ModuleStorage) -> Result<(), PluginError>;
239}
240
241/// A plugin that registers one or more extension points.
242pub trait QrPlugin {
243    /// Stable plugin name.
244    fn name(&self) -> &str;
245
246    /// Plugin version string.
247    fn version(&self) -> &str;
248
249    /// Registers this plugin's extension points into `registry`.
250    fn register(&self, registry: &mut PluginRegistry);
251}
252
253/// Explicit plugin registry.
254#[derive(Default)]
255pub struct PluginRegistry {
256    renderers: BTreeMap<String, Box<dyn RendererFactory>>,
257    encoders: BTreeMap<String, Box<dyn EncoderFactory>>,
258    postprocessors: Vec<Box<dyn PostProcessor>>,
259}
260
261impl PluginRegistry {
262    /// Creates an empty registry.
263    #[must_use]
264    pub const fn new() -> Self {
265        Self { renderers: BTreeMap::new(), encoders: BTreeMap::new(), postprocessors: Vec::new() }
266    }
267
268    /// Registers all extension points provided by `plugin`.
269    pub fn register_plugin<P: QrPlugin + ?Sized>(&mut self, plugin: &P) {
270        plugin.register(self);
271    }
272
273    /// Registers or replaces a renderer factory by name.
274    pub fn register_renderer(
275        &mut self,
276        name: impl Into<String>,
277        factory: Box<dyn RendererFactory>,
278    ) -> Option<Box<dyn RendererFactory>> {
279        self.renderers.insert(name.into(), factory)
280    }
281
282    /// Registers or replaces an encoder factory by name.
283    pub fn register_encoder(
284        &mut self,
285        name: impl Into<String>,
286        factory: Box<dyn EncoderFactory>,
287    ) -> Option<Box<dyn EncoderFactory>> {
288        self.encoders.insert(name.into(), factory)
289    }
290
291    /// Appends a postprocessor to the registry.
292    pub fn register_postprocessor(&mut self, postprocessor: Box<dyn PostProcessor>) {
293        self.postprocessors.push(postprocessor);
294    }
295
296    /// Returns a renderer factory by name.
297    #[must_use]
298    pub fn renderer(&self, name: &str) -> Option<&dyn RendererFactory> {
299        self.renderers.get(name).map(Box::as_ref)
300    }
301
302    /// Builds a renderer by name.
303    ///
304    /// # Errors
305    ///
306    /// Returns [`PluginError::RendererNotFound`] when no renderer factory is
307    /// registered with `name`.
308    pub fn build_renderer(&self, name: &str, config: &RenderConfig) -> Result<Box<dyn DynRenderer>, PluginError> {
309        let factory = self.renderer(name).ok_or_else(|| PluginError::RendererNotFound(String::from(name)))?;
310        Ok(factory.build(config))
311    }
312
313    /// Returns an encoder factory by name.
314    #[must_use]
315    pub fn encoder(&self, name: &str) -> Option<&dyn EncoderFactory> {
316        self.encoders.get(name).map(Box::as_ref)
317    }
318
319    /// Builds an encoder by name.
320    ///
321    /// # Errors
322    ///
323    /// Returns [`PluginError::EncoderNotFound`] when no encoder factory is
324    /// registered with `name`.
325    pub fn build_encoder(&self, name: &str, config: &EncodeConfig) -> Result<Box<dyn DynEncoder>, PluginError> {
326        let factory = self.encoder(name).ok_or_else(|| PluginError::EncoderNotFound(String::from(name)))?;
327        Ok(factory.build(config))
328    }
329
330    /// Returns all postprocessors in registration order.
331    #[must_use]
332    pub fn postprocessors(&self) -> &[Box<dyn PostProcessor>] {
333        &self.postprocessors
334    }
335
336    /// Applies all registered postprocessors in registration order.
337    ///
338    /// # Errors
339    ///
340    /// Returns the first [`PluginError`] reported by a postprocessor.
341    pub fn process_modules(&self, modules: &mut dyn ModuleStorage) -> Result<(), PluginError> {
342        for postprocessor in &self.postprocessors {
343            postprocessor.process(modules)?;
344        }
345        Ok(())
346    }
347
348    /// Iterates renderer names in deterministic order.
349    pub fn renderer_names(&self) -> impl Iterator<Item = &str> {
350        self.renderers.keys().map(String::as_str)
351    }
352
353    /// Iterates encoder names in deterministic order.
354    pub fn encoder_names(&self) -> impl Iterator<Item = &str> {
355        self.encoders.keys().map(String::as_str)
356    }
357}
358
359#[cfg(test)]
360mod tests {
361    use super::{
362        DynEncoder, DynRenderer, EncodeConfig, EncodedOutput, EncoderFactory, ModuleGrid, PluginRegistry,
363        PostProcessor, QrPlugin, RenderConfig, RenderOutput, RendererFactory,
364    };
365    use crate::{Color, ModuleSource, ModuleStorage};
366    use alloc::boxed::Box;
367    use alloc::string::ToString;
368
369    struct TextRenderer {
370        dark: char,
371    }
372
373    impl DynRenderer for TextRenderer {
374        fn render(&self, code: &dyn ModuleSource) -> Result<RenderOutput, super::PluginError> {
375            let mut out = String::new();
376            for y in 0..code.height() {
377                for x in 0..code.width() {
378                    out.push(if code.get(x, y) == Color::Dark { self.dark } else { '.' });
379                }
380            }
381            Ok(RenderOutput::Text(out))
382        }
383    }
384
385    struct TextRendererFactory;
386
387    impl RendererFactory for TextRendererFactory {
388        fn build(&self, config: &RenderConfig) -> Box<dyn DynRenderer> {
389            let dark = config.option("dark").and_then(|s| s.chars().next()).unwrap_or('#');
390            Box::new(TextRenderer { dark })
391        }
392    }
393
394    struct LengthEncoder;
395
396    impl DynEncoder for LengthEncoder {
397        fn encode(&self, input: &[u8]) -> Result<EncodedOutput, super::PluginError> {
398            Ok(EncodedOutput::Bytes(input.len().to_string().into_bytes()))
399        }
400    }
401
402    struct LengthEncoderFactory;
403
404    impl EncoderFactory for LengthEncoderFactory {
405        fn build(&self, _config: &EncodeConfig) -> Box<dyn DynEncoder> {
406            Box::new(LengthEncoder)
407        }
408    }
409
410    struct FlipFirst;
411
412    impl PostProcessor for FlipFirst {
413        fn process(&self, modules: &mut dyn ModuleStorage) -> Result<(), super::PluginError> {
414            modules.set(0, 0, Color::Dark);
415            Ok(())
416        }
417    }
418
419    struct FailPostprocessor;
420
421    impl PostProcessor for FailPostprocessor {
422        fn process(&self, _modules: &mut dyn ModuleStorage) -> Result<(), super::PluginError> {
423            Err(super::PluginError::PostProcessFailed("boom".into()))
424        }
425    }
426
427    struct DemoPlugin;
428
429    impl QrPlugin for DemoPlugin {
430        fn name(&self) -> &str {
431            "demo"
432        }
433
434        fn version(&self) -> &str {
435            "0.1.0"
436        }
437
438        fn register(&self, registry: &mut PluginRegistry) {
439            registry.register_renderer("text", Box::new(TextRendererFactory));
440            registry.register_encoder("length", Box::new(LengthEncoderFactory));
441            registry.register_postprocessor(Box::new(FlipFirst));
442        }
443    }
444
445    #[test]
446    fn registry_registers_and_uses_plugin_extension_points() {
447        let mut registry = PluginRegistry::new();
448        registry.register_plugin(&DemoPlugin);
449
450        let grid = ModuleGrid::new(alloc::vec![Color::Dark, Color::Light, Color::Light, Color::Dark], 2, 2).unwrap();
451        let config = RenderConfig::new().with_option("dark", "X");
452        let renderer = registry.build_renderer("text", &config).unwrap();
453        assert_eq!(renderer.render(&grid).unwrap(), RenderOutput::Text("X..X".into()));
454
455        let encoder = registry.build_encoder("length", &EncodeConfig::new()).unwrap();
456        assert_eq!(encoder.encode(b"abcd").unwrap(), EncodedOutput::Bytes(b"4".to_vec()));
457    }
458
459    #[test]
460    fn build_renderer_reports_missing_renderer_name() {
461        let registry = PluginRegistry::new();
462
463        assert!(matches!(
464            registry.build_renderer("missing", &RenderConfig::new()),
465            Err(super::PluginError::RendererNotFound(name)) if name == "missing"
466        ));
467    }
468
469    #[test]
470    fn build_encoder_reports_missing_encoder_name() {
471        let registry = PluginRegistry::new();
472
473        assert!(matches!(
474            registry.build_encoder("missing", &EncodeConfig::new()),
475            Err(super::PluginError::EncoderNotFound(name)) if name == "missing"
476        ));
477    }
478
479    #[test]
480    fn registry_keeps_names_deterministic() {
481        let mut registry = PluginRegistry::new();
482        registry.register_renderer("zeta", Box::new(TextRendererFactory));
483        registry.register_renderer("alpha", Box::new(TextRendererFactory));
484
485        let names = registry.renderer_names().collect::<Vec<_>>();
486        assert_eq!(names, ["alpha", "zeta"]);
487    }
488
489    #[test]
490    fn postprocessors_mutate_module_storage_in_order() {
491        let mut registry = PluginRegistry::new();
492        registry.register_postprocessor(Box::new(FlipFirst));
493        let mut grid = ModuleGrid::new(alloc::vec![Color::Light; 4], 2, 2).unwrap();
494
495        registry.process_modules(&mut grid).unwrap();
496
497        assert_eq!(ModuleSource::get(&grid, 0, 0), Color::Dark);
498    }
499
500    #[test]
501    fn process_modules_stops_on_first_postprocessor_error() {
502        let mut registry = PluginRegistry::new();
503        registry.register_postprocessor(Box::new(FailPostprocessor));
504        let mut grid = ModuleGrid::new(alloc::vec![Color::Light; 4], 2, 2).unwrap();
505
506        assert!(matches!(
507            registry.process_modules(&mut grid),
508            Err(super::PluginError::PostProcessFailed(message)) if message == "boom"
509        ));
510    }
511}