qrcode-core 2.0.0

Zero-dependency QR code encoding core (no_std + alloc) — the encoding primitive layer of qrcode-rs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! Explicit plugin registry and object-safe extension points.
//!
//! The registry is intentionally local state: callers create a
//! [`PluginRegistry`], register plugins into it, and pass it to facade or
//! application code. This keeps plugin behavior deterministic and avoids hidden
//! global mutation.

use crate::{Color, ModuleSource, ModuleStorage};
use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;

/// Error type used by object-safe plugin entry points.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PluginError {
    /// A named renderer was not present in the registry.
    RendererNotFound(String),

    /// A named encoder was not present in the registry.
    EncoderNotFound(String),

    /// The plugin configuration was invalid.
    InvalidConfig(String),

    /// A module grid shape was invalid.
    InvalidModuleGrid,

    /// A renderer failed.
    RenderFailed(String),

    /// An encoder failed.
    EncodeFailed(String),

    /// A postprocessor failed.
    PostProcessFailed(String),
}

impl fmt::Display for PluginError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::RendererNotFound(name) => write!(f, "renderer plugin not found: {name}"),
            Self::EncoderNotFound(name) => write!(f, "encoder plugin not found: {name}"),
            Self::InvalidConfig(message) => write!(f, "invalid plugin config: {message}"),
            Self::InvalidModuleGrid => f.write_str("invalid module grid"),
            Self::RenderFailed(message) => write!(f, "renderer plugin failed: {message}"),
            Self::EncodeFailed(message) => write!(f, "encoder plugin failed: {message}"),
            Self::PostProcessFailed(message) => write!(f, "postprocessor plugin failed: {message}"),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for PluginError {}

/// Runtime renderer configuration passed to renderer factories.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RenderConfig {
    format: Option<String>,
    options: BTreeMap<String, String>,
}

impl RenderConfig {
    /// Creates an empty render configuration.
    #[must_use]
    pub const fn new() -> Self {
        Self { format: None, options: BTreeMap::new() }
    }

    /// Sets the requested output format.
    #[must_use]
    pub fn with_format(mut self, format: impl Into<String>) -> Self {
        self.format = Some(format.into());
        self
    }

    /// Adds or replaces an arbitrary string option.
    #[must_use]
    pub fn with_option(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.options.insert(key.into(), value.into());
        self
    }

    /// Returns the requested output format, if one was configured.
    #[must_use]
    pub fn format(&self) -> Option<&str> {
        self.format.as_deref()
    }

    /// Returns a string option by key.
    #[must_use]
    pub fn option(&self, key: &str) -> Option<&str> {
        self.options.get(key).map(String::as_str)
    }
}

/// Runtime encoder configuration passed to encoder factories.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct EncodeConfig {
    options: BTreeMap<String, String>,
}

impl EncodeConfig {
    /// Creates an empty encode configuration.
    #[must_use]
    pub const fn new() -> Self {
        Self { options: BTreeMap::new() }
    }

    /// Adds or replaces an arbitrary string option.
    #[must_use]
    pub fn with_option(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.options.insert(key.into(), value.into());
        self
    }

    /// Returns a string option by key.
    #[must_use]
    pub fn option(&self, key: &str) -> Option<&str> {
        self.options.get(key).map(String::as_str)
    }
}

/// Type-erased render output returned by dynamic renderers.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RenderOutput {
    /// Text output such as SVG, HTML, ANSI, or plain strings.
    Text(String),

    /// Binary output such as PNG, PDF, or other encoded bytes.
    Bytes(Vec<u8>),

    /// A module-grid output for plugins that transform but do not serialize.
    Modules(ModuleGrid),
}

/// Type-erased encode output returned by dynamic encoders.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EncodedOutput {
    /// Encoded QR modules.
    Modules(ModuleGrid),

    /// Opaque encoded bytes.
    Bytes(Vec<u8>),
}

/// Owned mutable module grid used by plugin postprocessors.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ModuleGrid {
    modules: Vec<Color>,
    width: usize,
    height: usize,
}

impl ModuleGrid {
    /// Creates a module grid from row-major modules.
    ///
    /// # Errors
    ///
    /// Returns [`PluginError::InvalidModuleGrid`] when the dimensions are zero
    /// or `modules.len() != width * height`.
    pub fn new(modules: Vec<Color>, width: usize, height: usize) -> Result<Self, PluginError> {
        if width == 0 || height == 0 || modules.len() != width * height {
            return Err(PluginError::InvalidModuleGrid);
        }
        Ok(Self { modules, width, height })
    }

    /// Returns the grid modules as a mutable row-major slice.
    #[must_use]
    pub fn modules_mut(&mut self) -> &mut [Color] {
        &mut self.modules
    }
}

impl ModuleStorage for ModuleGrid {
    fn get(&self, x: usize, y: usize) -> Color {
        self.modules[y * self.width + x]
    }

    fn set(&mut self, x: usize, y: usize, color: Color) {
        self.modules[y * self.width + x] = color;
    }

    fn width(&self) -> usize {
        self.width
    }

    fn height(&self) -> usize {
        self.height
    }

    fn modules(&self) -> &[Color] {
        &self.modules
    }
}

/// Object-safe renderer used by [`RendererFactory`].
pub trait DynRenderer {
    /// Renders a module source.
    ///
    /// # Errors
    ///
    /// Returns [`PluginError`] when the renderer cannot produce output.
    fn render(&self, code: &dyn ModuleSource) -> Result<RenderOutput, PluginError>;
}

/// Factory for object-safe renderers.
pub trait RendererFactory {
    /// Builds a renderer from `config`.
    fn build(&self, config: &RenderConfig) -> Box<dyn DynRenderer>;
}

/// Object-safe encoder used by [`EncoderFactory`].
pub trait DynEncoder {
    /// Encodes raw input.
    ///
    /// # Errors
    ///
    /// Returns [`PluginError`] when the encoder cannot produce output.
    fn encode(&self, input: &[u8]) -> Result<EncodedOutput, PluginError>;
}

/// Factory for object-safe encoders.
pub trait EncoderFactory {
    /// Builds an encoder from `config`.
    fn build(&self, config: &EncodeConfig) -> Box<dyn DynEncoder>;
}

/// Object-safe postprocessor for in-place module-grid transforms.
pub trait PostProcessor {
    /// Processes `modules` in place.
    ///
    /// # Errors
    ///
    /// Returns [`PluginError`] when processing fails.
    fn process(&self, modules: &mut dyn ModuleStorage) -> Result<(), PluginError>;
}

/// A plugin that registers one or more extension points.
pub trait QrPlugin {
    /// Stable plugin name.
    fn name(&self) -> &str;

    /// Plugin version string.
    fn version(&self) -> &str;

    /// Registers this plugin's extension points into `registry`.
    fn register(&self, registry: &mut PluginRegistry);
}

/// Explicit plugin registry.
#[derive(Default)]
pub struct PluginRegistry {
    renderers: BTreeMap<String, Box<dyn RendererFactory>>,
    encoders: BTreeMap<String, Box<dyn EncoderFactory>>,
    postprocessors: Vec<Box<dyn PostProcessor>>,
}

impl PluginRegistry {
    /// Creates an empty registry.
    #[must_use]
    pub const fn new() -> Self {
        Self { renderers: BTreeMap::new(), encoders: BTreeMap::new(), postprocessors: Vec::new() }
    }

    /// Registers all extension points provided by `plugin`.
    pub fn register_plugin<P: QrPlugin + ?Sized>(&mut self, plugin: &P) {
        plugin.register(self);
    }

    /// Registers or replaces a renderer factory by name.
    pub fn register_renderer(
        &mut self,
        name: impl Into<String>,
        factory: Box<dyn RendererFactory>,
    ) -> Option<Box<dyn RendererFactory>> {
        self.renderers.insert(name.into(), factory)
    }

    /// Registers or replaces an encoder factory by name.
    pub fn register_encoder(
        &mut self,
        name: impl Into<String>,
        factory: Box<dyn EncoderFactory>,
    ) -> Option<Box<dyn EncoderFactory>> {
        self.encoders.insert(name.into(), factory)
    }

    /// Appends a postprocessor to the registry.
    pub fn register_postprocessor(&mut self, postprocessor: Box<dyn PostProcessor>) {
        self.postprocessors.push(postprocessor);
    }

    /// Returns a renderer factory by name.
    #[must_use]
    pub fn renderer(&self, name: &str) -> Option<&dyn RendererFactory> {
        self.renderers.get(name).map(Box::as_ref)
    }

    /// Builds a renderer by name.
    ///
    /// # Errors
    ///
    /// Returns [`PluginError::RendererNotFound`] when no renderer factory is
    /// registered with `name`.
    pub fn build_renderer(&self, name: &str, config: &RenderConfig) -> Result<Box<dyn DynRenderer>, PluginError> {
        let factory = self.renderer(name).ok_or_else(|| PluginError::RendererNotFound(String::from(name)))?;
        Ok(factory.build(config))
    }

    /// Returns an encoder factory by name.
    #[must_use]
    pub fn encoder(&self, name: &str) -> Option<&dyn EncoderFactory> {
        self.encoders.get(name).map(Box::as_ref)
    }

    /// Builds an encoder by name.
    ///
    /// # Errors
    ///
    /// Returns [`PluginError::EncoderNotFound`] when no encoder factory is
    /// registered with `name`.
    pub fn build_encoder(&self, name: &str, config: &EncodeConfig) -> Result<Box<dyn DynEncoder>, PluginError> {
        let factory = self.encoder(name).ok_or_else(|| PluginError::EncoderNotFound(String::from(name)))?;
        Ok(factory.build(config))
    }

    /// Returns all postprocessors in registration order.
    #[must_use]
    pub fn postprocessors(&self) -> &[Box<dyn PostProcessor>] {
        &self.postprocessors
    }

    /// Applies all registered postprocessors in registration order.
    ///
    /// # Errors
    ///
    /// Returns the first [`PluginError`] reported by a postprocessor.
    pub fn process_modules(&self, modules: &mut dyn ModuleStorage) -> Result<(), PluginError> {
        for postprocessor in &self.postprocessors {
            postprocessor.process(modules)?;
        }
        Ok(())
    }

    /// Iterates renderer names in deterministic order.
    pub fn renderer_names(&self) -> impl Iterator<Item = &str> {
        self.renderers.keys().map(String::as_str)
    }

    /// Iterates encoder names in deterministic order.
    pub fn encoder_names(&self) -> impl Iterator<Item = &str> {
        self.encoders.keys().map(String::as_str)
    }
}

#[cfg(test)]
mod tests {
    use super::{
        DynEncoder, DynRenderer, EncodeConfig, EncodedOutput, EncoderFactory, ModuleGrid, PluginRegistry,
        PostProcessor, QrPlugin, RenderConfig, RenderOutput, RendererFactory,
    };
    use crate::{Color, ModuleSource, ModuleStorage};
    use alloc::boxed::Box;
    use alloc::string::ToString;

    struct TextRenderer {
        dark: char,
    }

    impl DynRenderer for TextRenderer {
        fn render(&self, code: &dyn ModuleSource) -> Result<RenderOutput, super::PluginError> {
            let mut out = String::new();
            for y in 0..code.height() {
                for x in 0..code.width() {
                    out.push(if code.get(x, y) == Color::Dark { self.dark } else { '.' });
                }
            }
            Ok(RenderOutput::Text(out))
        }
    }

    struct TextRendererFactory;

    impl RendererFactory for TextRendererFactory {
        fn build(&self, config: &RenderConfig) -> Box<dyn DynRenderer> {
            let dark = config.option("dark").and_then(|s| s.chars().next()).unwrap_or('#');
            Box::new(TextRenderer { dark })
        }
    }

    struct LengthEncoder;

    impl DynEncoder for LengthEncoder {
        fn encode(&self, input: &[u8]) -> Result<EncodedOutput, super::PluginError> {
            Ok(EncodedOutput::Bytes(input.len().to_string().into_bytes()))
        }
    }

    struct LengthEncoderFactory;

    impl EncoderFactory for LengthEncoderFactory {
        fn build(&self, _config: &EncodeConfig) -> Box<dyn DynEncoder> {
            Box::new(LengthEncoder)
        }
    }

    struct FlipFirst;

    impl PostProcessor for FlipFirst {
        fn process(&self, modules: &mut dyn ModuleStorage) -> Result<(), super::PluginError> {
            modules.set(0, 0, Color::Dark);
            Ok(())
        }
    }

    struct FailPostprocessor;

    impl PostProcessor for FailPostprocessor {
        fn process(&self, _modules: &mut dyn ModuleStorage) -> Result<(), super::PluginError> {
            Err(super::PluginError::PostProcessFailed("boom".into()))
        }
    }

    struct DemoPlugin;

    impl QrPlugin for DemoPlugin {
        fn name(&self) -> &str {
            "demo"
        }

        fn version(&self) -> &str {
            "0.1.0"
        }

        fn register(&self, registry: &mut PluginRegistry) {
            registry.register_renderer("text", Box::new(TextRendererFactory));
            registry.register_encoder("length", Box::new(LengthEncoderFactory));
            registry.register_postprocessor(Box::new(FlipFirst));
        }
    }

    #[test]
    fn registry_registers_and_uses_plugin_extension_points() {
        let mut registry = PluginRegistry::new();
        registry.register_plugin(&DemoPlugin);

        let grid = ModuleGrid::new(alloc::vec![Color::Dark, Color::Light, Color::Light, Color::Dark], 2, 2).unwrap();
        let config = RenderConfig::new().with_option("dark", "X");
        let renderer = registry.build_renderer("text", &config).unwrap();
        assert_eq!(renderer.render(&grid).unwrap(), RenderOutput::Text("X..X".into()));

        let encoder = registry.build_encoder("length", &EncodeConfig::new()).unwrap();
        assert_eq!(encoder.encode(b"abcd").unwrap(), EncodedOutput::Bytes(b"4".to_vec()));
    }

    #[test]
    fn build_renderer_reports_missing_renderer_name() {
        let registry = PluginRegistry::new();

        assert!(matches!(
            registry.build_renderer("missing", &RenderConfig::new()),
            Err(super::PluginError::RendererNotFound(name)) if name == "missing"
        ));
    }

    #[test]
    fn build_encoder_reports_missing_encoder_name() {
        let registry = PluginRegistry::new();

        assert!(matches!(
            registry.build_encoder("missing", &EncodeConfig::new()),
            Err(super::PluginError::EncoderNotFound(name)) if name == "missing"
        ));
    }

    #[test]
    fn registry_keeps_names_deterministic() {
        let mut registry = PluginRegistry::new();
        registry.register_renderer("zeta", Box::new(TextRendererFactory));
        registry.register_renderer("alpha", Box::new(TextRendererFactory));

        let names = registry.renderer_names().collect::<Vec<_>>();
        assert_eq!(names, ["alpha", "zeta"]);
    }

    #[test]
    fn postprocessors_mutate_module_storage_in_order() {
        let mut registry = PluginRegistry::new();
        registry.register_postprocessor(Box::new(FlipFirst));
        let mut grid = ModuleGrid::new(alloc::vec![Color::Light; 4], 2, 2).unwrap();

        registry.process_modules(&mut grid).unwrap();

        assert_eq!(ModuleSource::get(&grid, 0, 0), Color::Dark);
    }

    #[test]
    fn process_modules_stops_on_first_postprocessor_error() {
        let mut registry = PluginRegistry::new();
        registry.register_postprocessor(Box::new(FailPostprocessor));
        let mut grid = ModuleGrid::new(alloc::vec![Color::Light; 4], 2, 2).unwrap();

        assert!(matches!(
            registry.process_modules(&mut grid),
            Err(super::PluginError::PostProcessFailed(message)) if message == "boom"
        ));
    }
}