rubo4e 0.13.0

Rust implementation of the BO4E energy-market data standard
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
//! Macros that stamp out the parts of an identifier newtype which are identical
//! for every type in this module.
//!
//! Each identifier is a `Box<str>` newtype whose only interesting piece is its
//! `validate` function. Everything else โ€” the conversion traits, the wire-format
//! traits, and the `serde` impls โ€” is mechanical. Writing those by hand once per
//! type produced ~60 lines of duplicated code per identifier and made it easy for
//! a type to silently drift (e.g. gain a `Deserialize` that skips validation).
//!
//! [`impl_identifier_traits!`] generates that shared surface, and
//! [`bdew_ascii_identifier!`] generates a whole ยง8.2 ASCII-Verfahren identifier
//! (NeLo-ID, NeBe-ID, TR/SR/SG/CR-ID, Paket-ID), which differ only in their
//! Codetyp prefix and documentation.

/// Implements the conversion, wire-format, and `serde` traits shared by every
/// identifier newtype.
///
/// The type must be a single-field tuple struct wrapping `Box<str>` and provide
/// an inherent `fn new(&str) -> Result<Self, IdentifierError>` that performs all
/// validation. Deserialization routes through `new`, so a value that exists can
/// always be trusted to have been validated.
macro_rules! impl_identifier_traits {
    // Tuple-struct form: the string lives in field `.0`.
    ($ty:ident, $expecting:expr) => {
        impl_identifier_traits!($ty, $expecting, field = 0);
    };
    // Named-field form, for identifiers that also cache parsed data alongside
    // the string (e.g. `ObisCode`).
    ($ty:ident, $expecting:expr, field = $field:tt) => {
        impl TryFrom<String> for $ty {
            type Error = $crate::error::IdentifierError;
            fn try_from(s: String) -> Result<Self, Self::Error> {
                Self::new(&s)
            }
        }

        impl TryFrom<&str> for $ty {
            type Error = $crate::error::IdentifierError;
            fn try_from(s: &str) -> Result<Self, Self::Error> {
                Self::new(s)
            }
        }

        impl AsRef<str> for $ty {
            #[inline]
            fn as_ref(&self) -> &str {
                &self.$field
            }
        }

        impl std::borrow::Borrow<str> for $ty {
            #[inline]
            fn borrow(&self) -> &str {
                &self.$field
            }
        }

        impl std::ops::Deref for $ty {
            type Target = str;
            #[inline]
            fn deref(&self) -> &str {
                &self.$field
            }
        }

        impl std::fmt::Display for $ty {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str(&self.$field)
            }
        }

        impl std::str::FromStr for $ty {
            type Err = $crate::error::IdentifierError;
            fn from_str(s: &str) -> Result<Self, Self::Err> {
                Self::new(s)
            }
        }

        impl From<$ty> for String {
            fn from(id: $ty) -> String {
                String::from(id.$field)
            }
        }

        #[cfg(feature = "serde")]
        impl serde::Serialize for $ty {
            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
                s.serialize_str(&self.$field)
            }
        }

        #[cfg(feature = "serde")]
        impl<'de> serde::Deserialize<'de> for $ty {
            fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
                struct Visitor;
                impl serde::de::Visitor<'_> for Visitor {
                    type Value = $ty;
                    fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                        f.write_str($expecting)
                    }
                    fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<$ty, E> {
                        $ty::new(v).map_err(|e| {
                            $crate::identifiers::trace_identifier_deser_error(
                                stringify!($ty),
                                v,
                                &e,
                            );
                            serde::de::Error::custom(e)
                        })
                    }
                }
                d.deserialize_str(Visitor)
            }
        }
    };
}

/// Defines a complete BDEW ยง8.2 "ASCII-Verfahren" identifier newtype.
///
/// These identifiers are all 11 characters: a fixed Codetyp prefix, an
/// uppercase-alphanumeric body, and a numeric check digit at position 11. They
/// differ only in the prefix, so everything else is generated here.
///
/// Parameters:
/// - `$ty` โ€” the newtype name.
/// - `$prefix` โ€” the Codetyp byte string (e.g. `b"E"`, `b"P9"`).
/// - `$schema_fn` โ€” path to the `schemars` schema function.
/// - `$schema_meta` โ€” the type's entry in [`crate::identifiers::schema`], read by
///   both derives for the description.
/// - `$pattern` โ€” the same regex `$schema_meta` carries, as a literal: `utoipa`
///   compiles the regex and will not take an expression.
/// - `$expecting` โ€” the `serde` "expecting" message.
/// - `$example_base` / `$example_full` โ€” a doctest vector, and the OpenAPI
///   example; `$example_full` must be `$example_base` plus its check digit.
macro_rules! bdew_ascii_identifier {
    (
        $(#[$meta:meta])*
        $ty:ident,
        prefix     = $prefix:expr,
        schema     = $schema_fn:literal,
        schema_meta = $schema_meta:expr,
        pattern    = $pattern:literal,
        expecting  = $expecting:expr,
        example    = ($example_base:literal, $example_full:literal),
        check_fn   = $check_fn:ident $(,)?
    ) => {
        $(#[$meta])*
        ///
        /// # Examples
        /// ```
        #[doc = concat!("use rubo4e::identifiers::", stringify!($ty), ";")]
        ///
        #[doc = concat!("let id = ", stringify!($ty), "::new(\"", $example_full, "\").unwrap();")]
        #[doc = concat!("assert_eq!(id.to_string(), \"", $example_full, "\");")]
        ///
        /// // The check digit is derived, so it never has to be typed by hand:
        #[doc = concat!("let id = ", stringify!($ty), "::from_base(\"", $example_base, "\").unwrap();")]
        #[doc = concat!("assert_eq!(id.as_ref(), \"", $example_full, "\");")]
        /// ```
        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
        #[cfg_attr(feature = "validate", derive(garde::Validate))]
        #[cfg_attr(feature = "validate", garde(allow_unvalidated))]
        #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
        #[cfg_attr(feature = "schemars", schemars(schema_with = $schema_fn))]
        // Without this the derive substitutes the type's *rustdoc* for the
        // description โ€” overriding what `$schema_fn` writes, and putting Rust
        // prose and intra-doc links into a published JSON Schema.
        #[cfg_attr(feature = "schemars", schemars(description = $schema_meta.description))]
        #[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
        // `pattern` and `example` are literals because `utoipa` validates the
        // regex at compile time and so will not take an expression. They repeat
        // what `$schema_meta` holds; `tests/identifier_schemas.rs` asserts the
        // two never disagree.
        #[cfg_attr(feature = "utoipa", schema(
            value_type = String,
            pattern = $pattern,
            example = $example_full,
            description = $schema_meta.description
        ))]
        pub struct $ty(#[cfg_attr(feature = "validate", garde(custom($check_fn)))] Box<str>);

        #[cfg(feature = "validate")]
        fn $check_fn(value: &str, _: &()) -> Result<(), garde::Error> {
            $crate::identifiers::checksum::validate_ascii_id(value, $prefix)
                .map_err(garde::Error::from)
        }

        impl $ty {
            /// The fixed Codetyp prefix for this identifier type.
            pub const CODETYP: &'static str = match std::str::from_utf8($prefix) {
                Ok(s) => s,
                Err(_) => panic!("Codetyp prefix must be valid UTF-8"),
            };

            #[doc = concat!("Creates a new `", stringify!($ty), "` after full validation.")]
            ///
            /// # Errors
            /// - [`IdentifierError::InvalidLength`] if `s` is not exactly 11 characters.
            #[doc = concat!("- [`IdentifierError::InvalidFormat`] if `s` does not start with `\"", $example_base, "\"`'s Codetyp.")]
            /// - [`IdentifierError::InvalidCharacter`] if the body is not `[A-Z0-9]`,
            ///   or position 11 is not a decimal digit.
            /// - [`IdentifierError::InvalidChecksum`] if position 11 does not match the
            ///   ASCII-Verfahren check digit computed from positions 1โ€“10.
            ///
            /// [`IdentifierError::InvalidLength`]: crate::error::IdentifierError::InvalidLength
            /// [`IdentifierError::InvalidFormat`]: crate::error::IdentifierError::InvalidFormat
            /// [`IdentifierError::InvalidCharacter`]: crate::error::IdentifierError::InvalidCharacter
            /// [`IdentifierError::InvalidChecksum`]: crate::error::IdentifierError::InvalidChecksum
            #[must_use = "the validated identifier is returned; ignoring it discards the result"]
            pub fn new(s: &str) -> Result<Self, $crate::error::IdentifierError> {
                $crate::identifiers::checksum::validate_ascii_id(s, $prefix)?;
                Ok(Self(Box::from(s)))
            }

            #[doc = concat!("Builds a `", stringify!($ty), "` from its 10-character base by computing")]
            /// and appending the ASCII-Verfahren check digit.
            ///
            /// # Errors
            /// Same as [`new`](Self::new), minus the checksum error โ€” the check digit
            /// is computed rather than verified.
            pub fn from_base(base: &str) -> Result<Self, $crate::error::IdentifierError> {
                let full =
                    $crate::identifiers::checksum::compute_ascii_id_from_base(base, $prefix)?;
                Ok(Self(full.into_boxed_str()))
            }

            /// Computes the ASCII-Verfahren check digit (`0`โ€“`9`) for a 10-character
            /// base without constructing the identifier.
            ///
            /// # Errors
            /// Same as [`from_base`](Self::from_base).
            pub fn check_digit(base: &str) -> Result<u8, $crate::error::IdentifierError> {
                let full =
                    $crate::identifiers::checksum::compute_ascii_id_from_base(base, $prefix)?;
                Ok(full.as_bytes()[10] - b'0')
            }

            /// Returns the 10-character base (everything except the check digit).
            #[must_use]
            pub fn base(&self) -> &str {
                &self.0[..10]
            }
        }

        impl_identifier_traits!($ty, $expecting);
    };
}

/// Defines an identifier newtype that is an [`EicCode`] pinned to one ENTSO-E
/// object type.
///
/// The German market reuses the EIC namespace for several distinct roles that
/// differ *only* in the position-3 object-type character โ€” a Bilanzkreis is
/// `11Xโ€ฆ` (party), a Bilanzierungsgebiet is `11Yโ€ฆ` (area).  Each gets its own
/// Rust type so the two cannot be swapped at a call site, and everything except
/// the pinned character and the documentation is generated here.
///
/// Parameters:
/// - `$ty` โ€” the newtype name.
/// - `$eic_type` โ€” the [`EicType`] variant this identifier is restricted to.
/// - `$schema_fn` โ€” path to the `schemars` schema function.
/// - `$schema_meta` โ€” the type's entry in [`crate::identifiers::schema`], read by
///   both derives for the description.
/// - `$pattern` โ€” the same regex `$schema_meta` carries, as a literal: `utoipa`
///   compiles the regex and will not take an expression.
/// - `$expecting` โ€” the `serde` "expecting" message.
/// - `$example` โ€” a real 16-character code, used in the doctest and as the
///   OpenAPI example.
///
/// [`EicCode`]: crate::identifiers::EicCode
/// [`EicType`]: crate::identifiers::EicType
macro_rules! eic_restricted_identifier {
    (
        $(#[$meta:meta])*
        $ty:ident,
        eic_type   = $eic_type:expr,
        schema     = $schema_fn:literal,
        schema_meta = $schema_meta:expr,
        pattern    = $pattern:literal,
        expecting  = $expecting:expr,
        example    = $example:literal,
        check_fn   = $check_fn:ident $(,)?
    ) => {
        $(#[$meta])*
        ///
        /// # Examples
        /// ```
        #[doc = concat!("use rubo4e::identifiers::{", stringify!($ty), ", EicCode, EicType};")]
        ///
        #[doc = concat!("let id = ", stringify!($ty), "::new(\"", $example, "\").unwrap();")]
        #[doc = concat!("assert_eq!(id.to_string(), \"", $example, "\");")]
        #[doc = concat!("assert_eq!(", stringify!($ty), "::EIC_TYPE, ", stringify!($eic_type), ");")]
        ///
        /// // Widening to the general EIC type is infallible.
        /// let eic: EicCode = id.into();
        #[doc = concat!("assert_eq!(eic.eic_type(), ", stringify!($eic_type), ");")]
        /// ```
        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
        #[cfg_attr(feature = "validate", derive(garde::Validate))]
        #[cfg_attr(feature = "validate", garde(allow_unvalidated))]
        #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
        #[cfg_attr(feature = "schemars", schemars(schema_with = $schema_fn))]
        // Without this the derive substitutes the type's *rustdoc* for the
        // description โ€” overriding what `$schema_fn` writes, and putting Rust
        // prose and intra-doc links into a published JSON Schema.
        #[cfg_attr(feature = "schemars", schemars(description = $schema_meta.description))]
        #[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
        // `pattern` and `example` are literals because `utoipa` validates the
        // regex at compile time and so will not take an expression. They repeat
        // what `$schema_meta` holds; `tests/identifier_schemas.rs` asserts the
        // two never disagree.
        #[cfg_attr(feature = "utoipa", schema(
            value_type = String,
            pattern = $pattern,
            example = $example,
            description = $schema_meta.description
        ))]
        pub struct $ty(#[cfg_attr(feature = "validate", garde(custom($check_fn)))] Box<str>);

        #[cfg(feature = "validate")]
        fn $check_fn(value: &str, _: &()) -> Result<(), garde::Error> {
            $ty::validate(value).map_err(garde::Error::from)
        }

        impl $ty {
            /// The ENTSO-E object type every value of this type carries in position 3.
            pub const EIC_TYPE: $crate::identifiers::EicType = $eic_type;

            fn validate(s: &str) -> Result<(), $crate::error::IdentifierError> {
                // Full EIC validation first: length, alphabet, object type, check character.
                let eic = $crate::identifiers::EicCode::new(s)?;
                if eic.eic_type() != Self::EIC_TYPE {
                    return Err($crate::error::IdentifierError::InvalidFormat {
                        description: format!(
                            "{} requires EIC object type '{}' ({}) at position 3, found '{}' ({})",
                            stringify!($ty),
                            Self::EIC_TYPE.as_char(),
                            Self::EIC_TYPE.description(),
                            eic.type_char(),
                            eic.eic_type().description(),
                        )
                        .into(),
                    });
                }
                Ok(())
            }

            #[doc = concat!("Creates a new `", stringify!($ty), "` after full EIC validation,")]
            #[doc = concat!("requiring object type `", stringify!($eic_type), "` at position 3.")]
            ///
            /// # Errors
            /// - [`IdentifierError::InvalidLength`] if `s` is not exactly 16 characters.
            /// - [`IdentifierError::InvalidCharacter`] if any character is outside `[A-Z0-9-]`.
            /// - [`IdentifierError::InvalidFormat`] if position 3 is not this type's
            ///   object-type character.
            /// - [`IdentifierError::InvalidChecksum`] if position 16 is not the correct
            ///   ENTSO-E check character.
            ///
            /// [`IdentifierError::InvalidLength`]: crate::error::IdentifierError::InvalidLength
            /// [`IdentifierError::InvalidFormat`]: crate::error::IdentifierError::InvalidFormat
            /// [`IdentifierError::InvalidCharacter`]: crate::error::IdentifierError::InvalidCharacter
            /// [`IdentifierError::InvalidChecksum`]: crate::error::IdentifierError::InvalidChecksum
            #[must_use = "the validated identifier is returned; ignoring it discards the result"]
            pub fn new(s: &str) -> Result<Self, $crate::error::IdentifierError> {
                Self::validate(s)?;
                Ok(Self(Box::from(s)))
            }

            #[doc = concat!("Builds a `", stringify!($ty), "` from its 15-character prefix by")]
            /// computing and appending the ENTSO-E check character.
            ///
            /// # Errors
            /// - [`IdentifierError::InvalidLength`] if `prefix` is not exactly 15 characters.
            /// - [`IdentifierError::InvalidFormat`] if `prefix` is not ASCII or position 3
            ///   is not this type's object-type character.
            /// - [`IdentifierError::InvalidChecksum`] if the check character cannot be
            ///   computed (ENTSO-E prohibits `'-'` as a check character).
            ///
            /// [`IdentifierError::InvalidLength`]: crate::error::IdentifierError::InvalidLength
            /// [`IdentifierError::InvalidFormat`]: crate::error::IdentifierError::InvalidFormat
            /// [`IdentifierError::InvalidChecksum`]: crate::error::IdentifierError::InvalidChecksum
            pub fn from_prefix(prefix: &str) -> Result<Self, $crate::error::IdentifierError> {
                let full = $crate::identifiers::EicCode::complete_prefix(prefix)?;
                Self::new(&full)
            }

            /// Returns this value as a general [`EicCode`](crate::identifiers::EicCode).
            #[must_use]
            pub fn to_eic_code(&self) -> $crate::identifiers::EicCode {
                $crate::identifiers::EicCode::new(&self.0)
                    .expect(concat!(stringify!($ty), " is always a valid EicCode"))
            }
        }

        impl From<$ty> for $crate::identifiers::EicCode {
            fn from(id: $ty) -> Self {
                id.to_eic_code()
            }
        }

        impl TryFrom<$crate::identifiers::EicCode> for $ty {
            type Error = $crate::error::IdentifierError;
            fn try_from(eic: $crate::identifiers::EicCode) -> Result<Self, Self::Error> {
                Self::new(eic.as_ref())
            }
        }

        impl_identifier_traits!($ty, $expecting);
    };
}