Skip to main content

xsd_parser/pipeline/generator/
custom.rs

1use std::fmt::{Debug, Formatter, Result as FmtResult};
2
3use crate::pipeline::renderer::ValueRenderer;
4
5use super::{Context, Error};
6
7/// Boxed version of [`ValueGenerator`].
8pub type ValueGeneratorBox = Box<dyn ValueGenerator>;
9
10impl Debug for ValueGeneratorBox {
11    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
12        f.debug_struct("ValueGeneratorBox").finish()
13    }
14}
15
16/// Trait that converts the value of a element specified in the XML schema to
17/// actual code.
18///
19/// You can add a custom default value implementation to your custom type using
20/// [`CustomMeta::with_default`](crate::models::meta::CustomMeta::with_default).
21pub trait ValueGenerator: Send + Sync + 'static {
22    /// Try to convert the passed string `value` that contains the default value from
23    /// the XML schema to actual default code. If the value could not be converted
24    /// to code `None` is returned.
25    fn exec(
26        &self,
27        ctx: &Context<'_, '_>,
28        value: &str,
29        mode: ValueGeneratorMode,
30    ) -> Result<Box<dyn ValueRenderer>, Error>;
31
32    /// Clone this instance and return it as a box.
33    fn clone(&self) -> Box<dyn ValueGenerator>;
34}
35
36/// Determines how the value of a element specified in the XML schema should be converted to
37/// code.
38#[derive(Debug, Clone, Copy, Eq, PartialEq)]
39pub enum ValueGeneratorMode {
40    /// Render the value as a byte string literal.
41    Literal,
42
43    /// Render the value as a constant/compile time constructed value.
44    Constant,
45
46    /// Render the value as normal runtime constructed value.
47    Value,
48}
49
50impl<X> ValueGenerator for X
51where
52    X: Fn(&Context<'_, '_>, &str, ValueGeneratorMode) -> Result<Box<dyn ValueRenderer>, Error>
53        + Clone
54        + Send
55        + Sync
56        + 'static,
57{
58    fn exec(
59        &self,
60        ctx: &Context<'_, '_>,
61        value: &str,
62        mode: ValueGeneratorMode,
63    ) -> Result<Box<dyn ValueRenderer>, Error> {
64        (*self)(ctx, value, mode)
65    }
66
67    fn clone(&self) -> Box<dyn ValueGenerator> {
68        Box::new(self.clone())
69    }
70}