Skip to main content

fhir_types/stu3/
primitives.rs

1// @generated by fhir-codegen from hl7.fhir.r3.core 3.0.2. DO NOT EDIT.
2// Change the emitter (tools/fhir-codegen) and regenerate.
3// SPDX-FileCopyrightText: Cadasto B.V.
4// SPDX-License-Identifier: Apache-2.0
5//! The FHIR primitive types (<https://hl7.org/fhir/STU3/datatypes.html#primitive>).
6
7/// Primitive Type base64Binary
8///
9/// A stream of bytes
10#[derive(Debug, Clone, Default, PartialEq, Eq)]
11pub struct Base64Binary {
12    /// xml:id (or equivalent in JSON)
13    ///
14    /// unique id for the element within a resource (for internal references)
15    pub id: Option<std::string::String>,
16    /// Additional Content defined by implementations
17    ///
18    /// May be used to represent additional information that is not part of the
19    /// basic definition of the resource. In order to make the use of extensions
20    /// safe and manageable, there is a strict set of governance applied to the
21    /// definition and use of extensions. Though any implementer is allowed to
22    /// define an extension, there is a set of requirements that SHALL be met as
23    /// part of the definition of the extension.
24    pub extension: Vec<super::extension::Extension>,
25    /// Primitive value for base64Binary
26    ///
27    /// The actual value
28    pub value: Option<std::string::String>,
29}
30impl From<std::string::String> for Base64Binary {
31    fn from(value: std::string::String) -> Self {
32        Self {
33            value: Some(value),
34            ..Self::default()
35        }
36    }
37}
38impl From<&str> for Base64Binary {
39    fn from(value: &str) -> Self {
40        Self::from(std::string::String::from(value))
41    }
42}
43
44impl super::super::codec::Primitive for Base64Binary {
45    fn value_json(
46        &self,
47    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
48        Ok(self
49            .value
50            .as_ref()
51            .map(|v| super::super::codec::Value::String(v.clone())))
52    }
53
54    fn element_json(
55        &self,
56    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
57        if self.id.is_none() && self.extension.is_empty() {
58            return Ok(None);
59        }
60        let mut object = super::super::codec::Object::new();
61        if let Some(id) = &self.id {
62            object.insert(
63                std::string::String::from("id"),
64                super::super::codec::Value::String(id.clone()),
65            );
66        }
67        if !self.extension.is_empty() {
68            let mut items = Vec::with_capacity(self.extension.len());
69            for item in &self.extension {
70                items.push(super::super::codec::Value::Object(
71                    super::super::codec::Json::to_json(item)?,
72                ));
73            }
74            object.insert(
75                std::string::String::from("extension"),
76                super::super::codec::Value::Array(items),
77            );
78        }
79        Ok(Some(super::super::codec::Value::Object(object)))
80    }
81
82    fn has_value(&self) -> bool {
83        self.value.is_some()
84    }
85
86    fn has_element(&self) -> bool {
87        self.id.is_some() || !self.extension.is_empty()
88    }
89
90    fn serialize_value<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
91        match self.value.as_ref() {
92            Some(v) => serde::Serializer::serialize_str(serializer, v),
93            None => serde::Serializer::serialize_none(serializer),
94        }
95    }
96
97    fn serialize_element<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
98        if self.id.is_none() && self.extension.is_empty() {
99            return serde::Serializer::serialize_none(serializer);
100        }
101        let mut map = serde::Serializer::serialize_map(serializer, None)?;
102        if !self.extension.is_empty() {
103            serde::ser::SerializeMap::serialize_entry(&mut map, "extension", &self.extension)?;
104        }
105        if let Some(id) = &self.id {
106            serde::ser::SerializeMap::serialize_entry(&mut map, "id", id)?;
107        }
108        serde::ser::SerializeMap::end(map)
109    }
110
111    fn from_json_parts(
112        value: Option<&super::super::codec::Value>,
113        element: Option<&super::super::codec::Value>,
114        path: &mut super::super::codec::Path,
115    ) -> Result<Self, super::super::codec::DecodeError> {
116        if value.is_none() && element.is_none() && !path.is_lenient() {
117            return Err(path.error(super::super::codec::DecodeErrorKind::MissingProperty));
118        }
119        let value = match value {
120            Some(value) => {
121                let value = super::super::codec::expect_single(value, path)?;
122                Some(super::super::codec::expect_string(value, path)?)
123            }
124            None => None,
125        };
126        let mut id = None;
127        let mut extension = Vec::new();
128        if let Some(element) = element {
129            let object = super::super::codec::expect_object(element, path)?;
130            for (key, item) in object {
131                match key.as_str() {
132                    "id" => {
133                        id =
134                            Some(path.with("id", |path| {
135                                super::super::codec::expect_string(item, path)
136                            })?);
137                    }
138                    "extension" => {
139                        for (index, entry) in super::super::codec::expect_array(item, path)?
140                            .iter()
141                            .enumerate()
142                        {
143                            extension.push(path.with_index("extension", index, |path| {
144                                super::super::codec::Json::from_json(
145                                    super::super::codec::expect_object(entry, path)?,
146                                    path,
147                                )
148                            })?);
149                        }
150                    }
151                    _ => {
152                        return path.with(key, |path| {
153                            Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
154                        });
155                    }
156                }
157            }
158        }
159        Ok(Self {
160            id,
161            extension,
162            value,
163        })
164    }
165}
166
167/// Primitive Type boolean
168///
169/// Value of "true" or "false"
170#[derive(Debug, Clone, Default, PartialEq, Eq)]
171pub struct Boolean {
172    /// xml:id (or equivalent in JSON)
173    ///
174    /// unique id for the element within a resource (for internal references)
175    pub id: Option<std::string::String>,
176    /// Additional Content defined by implementations
177    ///
178    /// May be used to represent additional information that is not part of the
179    /// basic definition of the resource. In order to make the use of extensions
180    /// safe and manageable, there is a strict set of governance applied to the
181    /// definition and use of extensions. Though any implementer is allowed to
182    /// define an extension, there is a set of requirements that SHALL be met as
183    /// part of the definition of the extension.
184    pub extension: Vec<super::extension::Extension>,
185    /// Primitive value for boolean
186    ///
187    /// The actual value
188    pub value: Option<bool>,
189}
190impl From<bool> for Boolean {
191    fn from(value: bool) -> Self {
192        Self {
193            value: Some(value),
194            ..Self::default()
195        }
196    }
197}
198
199impl super::super::codec::Primitive for Boolean {
200    fn value_json(
201        &self,
202    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
203        Ok(self
204            .value
205            .as_ref()
206            .map(|v| super::super::codec::Value::Bool(*v)))
207    }
208
209    fn element_json(
210        &self,
211    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
212        if self.id.is_none() && self.extension.is_empty() {
213            return Ok(None);
214        }
215        let mut object = super::super::codec::Object::new();
216        if let Some(id) = &self.id {
217            object.insert(
218                std::string::String::from("id"),
219                super::super::codec::Value::String(id.clone()),
220            );
221        }
222        if !self.extension.is_empty() {
223            let mut items = Vec::with_capacity(self.extension.len());
224            for item in &self.extension {
225                items.push(super::super::codec::Value::Object(
226                    super::super::codec::Json::to_json(item)?,
227                ));
228            }
229            object.insert(
230                std::string::String::from("extension"),
231                super::super::codec::Value::Array(items),
232            );
233        }
234        Ok(Some(super::super::codec::Value::Object(object)))
235    }
236
237    fn has_value(&self) -> bool {
238        self.value.is_some()
239    }
240
241    fn has_element(&self) -> bool {
242        self.id.is_some() || !self.extension.is_empty()
243    }
244
245    fn serialize_value<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
246        match self.value.as_ref() {
247            Some(v) => serde::Serializer::serialize_bool(serializer, *v),
248            None => serde::Serializer::serialize_none(serializer),
249        }
250    }
251
252    fn serialize_element<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
253        if self.id.is_none() && self.extension.is_empty() {
254            return serde::Serializer::serialize_none(serializer);
255        }
256        let mut map = serde::Serializer::serialize_map(serializer, None)?;
257        if !self.extension.is_empty() {
258            serde::ser::SerializeMap::serialize_entry(&mut map, "extension", &self.extension)?;
259        }
260        if let Some(id) = &self.id {
261            serde::ser::SerializeMap::serialize_entry(&mut map, "id", id)?;
262        }
263        serde::ser::SerializeMap::end(map)
264    }
265
266    fn from_json_parts(
267        value: Option<&super::super::codec::Value>,
268        element: Option<&super::super::codec::Value>,
269        path: &mut super::super::codec::Path,
270    ) -> Result<Self, super::super::codec::DecodeError> {
271        if value.is_none() && element.is_none() && !path.is_lenient() {
272            return Err(path.error(super::super::codec::DecodeErrorKind::MissingProperty));
273        }
274        let value = match value {
275            Some(value) => {
276                let value = super::super::codec::expect_single(value, path)?;
277                Some(super::super::codec::expect_bool(value, path)?)
278            }
279            None => None,
280        };
281        let mut id = None;
282        let mut extension = Vec::new();
283        if let Some(element) = element {
284            let object = super::super::codec::expect_object(element, path)?;
285            for (key, item) in object {
286                match key.as_str() {
287                    "id" => {
288                        id =
289                            Some(path.with("id", |path| {
290                                super::super::codec::expect_string(item, path)
291                            })?);
292                    }
293                    "extension" => {
294                        for (index, entry) in super::super::codec::expect_array(item, path)?
295                            .iter()
296                            .enumerate()
297                        {
298                            extension.push(path.with_index("extension", index, |path| {
299                                super::super::codec::Json::from_json(
300                                    super::super::codec::expect_object(entry, path)?,
301                                    path,
302                                )
303                            })?);
304                        }
305                    }
306                    _ => {
307                        return path.with(key, |path| {
308                            Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
309                        });
310                    }
311                }
312            }
313        }
314        Ok(Self {
315            id,
316            extension,
317            value,
318        })
319    }
320}
321
322/// Primitive Type code
323///
324/// A string which has at least one character and no leading or trailing
325/// whitespace and where there is no whitespace other than single spaces in the
326/// contents
327#[derive(Debug, Clone, Default, PartialEq, Eq)]
328pub struct Code {
329    /// xml:id (or equivalent in JSON)
330    ///
331    /// unique id for the element within a resource (for internal references)
332    pub id: Option<std::string::String>,
333    /// Additional Content defined by implementations
334    ///
335    /// May be used to represent additional information that is not part of the
336    /// basic definition of the resource. In order to make the use of extensions
337    /// safe and manageable, there is a strict set of governance applied to the
338    /// definition and use of extensions. Though any implementer is allowed to
339    /// define an extension, there is a set of requirements that SHALL be met as
340    /// part of the definition of the extension.
341    pub extension: Vec<super::extension::Extension>,
342    /// Primitive value for code
343    pub value: Option<std::string::String>,
344}
345impl From<std::string::String> for Code {
346    fn from(value: std::string::String) -> Self {
347        Self {
348            value: Some(value),
349            ..Self::default()
350        }
351    }
352}
353impl From<&str> for Code {
354    fn from(value: &str) -> Self {
355        Self::from(std::string::String::from(value))
356    }
357}
358
359/// The lexical form of the FHIR primitive `code`, anchored to the whole value.
360///
361/// The `regex` extension of `code.value` states it (<https://hl7.org/fhir/STU3/datatypes.html#primitive>),
362/// and the form is an XML Schema pattern, where `\s` is the space, the tab,
363/// the carriage return and the line feed alone (<https://www.w3.org/TR/xmlschema-2/#regexs>).
364#[expect(
365    clippy::expect_used,
366    reason = "the emitter compiles every lexical form it writes, so the pattern holds"
367)]
368static CODE_LEXICAL_FORM: std::sync::LazyLock<regex::bytes::Regex> =
369    std::sync::LazyLock::new(|| {
370        regex::bytes::RegexBuilder::new(r"^(?:[^\s]+([\s]?[^\s]+)*)$")
371            .unicode(false)
372            .build()
373            .expect("the lexical form of `code` should compile")
374    });
375
376/// Hands back `text` when it keeps the lexical form of `code`.
377///
378/// # Errors
379///
380/// Returns [`super::super::codec::DecodeErrorKind::BadValue`] at `path` for a value outside the form.
381pub(crate) fn checked_code(
382    text: std::string::String,
383    path: &super::super::codec::Path,
384) -> Result<std::string::String, super::super::codec::DecodeError> {
385    if CODE_LEXICAL_FORM.is_match(text.as_bytes()) {
386        Ok(text)
387    } else {
388        Err(path.error(super::super::codec::DecodeErrorKind::BadValue))
389    }
390}
391
392impl Code {
393    /// Checks `text` against the lexical form of `code`, the one the decoder holds a value to.
394    ///
395    /// # Errors
396    ///
397    /// Returns [`super::super::codec::LexicalError`] naming `code` when `text` is outside the form.
398    pub fn check(text: &str) -> Result<(), super::super::codec::LexicalError> {
399        if CODE_LEXICAL_FORM.is_match(text.as_bytes()) {
400            Ok(())
401        } else {
402            Err(super::super::codec::LexicalError { type_code: "code" })
403        }
404    }
405}
406
407impl super::super::codec::Primitive for Code {
408    fn value_json(
409        &self,
410    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
411        Ok(self
412            .value
413            .as_ref()
414            .map(|v| super::super::codec::Value::String(v.clone())))
415    }
416
417    fn element_json(
418        &self,
419    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
420        if self.id.is_none() && self.extension.is_empty() {
421            return Ok(None);
422        }
423        let mut object = super::super::codec::Object::new();
424        if let Some(id) = &self.id {
425            object.insert(
426                std::string::String::from("id"),
427                super::super::codec::Value::String(id.clone()),
428            );
429        }
430        if !self.extension.is_empty() {
431            let mut items = Vec::with_capacity(self.extension.len());
432            for item in &self.extension {
433                items.push(super::super::codec::Value::Object(
434                    super::super::codec::Json::to_json(item)?,
435                ));
436            }
437            object.insert(
438                std::string::String::from("extension"),
439                super::super::codec::Value::Array(items),
440            );
441        }
442        Ok(Some(super::super::codec::Value::Object(object)))
443    }
444
445    fn has_value(&self) -> bool {
446        self.value.is_some()
447    }
448
449    fn has_element(&self) -> bool {
450        self.id.is_some() || !self.extension.is_empty()
451    }
452
453    fn serialize_value<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
454        match self.value.as_ref() {
455            Some(v) => serde::Serializer::serialize_str(serializer, v),
456            None => serde::Serializer::serialize_none(serializer),
457        }
458    }
459
460    fn serialize_element<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
461        if self.id.is_none() && self.extension.is_empty() {
462            return serde::Serializer::serialize_none(serializer);
463        }
464        let mut map = serde::Serializer::serialize_map(serializer, None)?;
465        if !self.extension.is_empty() {
466            serde::ser::SerializeMap::serialize_entry(&mut map, "extension", &self.extension)?;
467        }
468        if let Some(id) = &self.id {
469            serde::ser::SerializeMap::serialize_entry(&mut map, "id", id)?;
470        }
471        serde::ser::SerializeMap::end(map)
472    }
473
474    fn from_json_parts(
475        value: Option<&super::super::codec::Value>,
476        element: Option<&super::super::codec::Value>,
477        path: &mut super::super::codec::Path,
478    ) -> Result<Self, super::super::codec::DecodeError> {
479        if value.is_none() && element.is_none() && !path.is_lenient() {
480            return Err(path.error(super::super::codec::DecodeErrorKind::MissingProperty));
481        }
482        let value = match value {
483            Some(value) => {
484                let value = super::super::codec::expect_single(value, path)?;
485                Some(checked_code(
486                    super::super::codec::expect_string(value, path)?,
487                    path,
488                )?)
489            }
490            None => None,
491        };
492        let mut id = None;
493        let mut extension = Vec::new();
494        if let Some(element) = element {
495            let object = super::super::codec::expect_object(element, path)?;
496            for (key, item) in object {
497                match key.as_str() {
498                    "id" => {
499                        id =
500                            Some(path.with("id", |path| {
501                                super::super::codec::expect_string(item, path)
502                            })?);
503                    }
504                    "extension" => {
505                        for (index, entry) in super::super::codec::expect_array(item, path)?
506                            .iter()
507                            .enumerate()
508                        {
509                            extension.push(path.with_index("extension", index, |path| {
510                                super::super::codec::Json::from_json(
511                                    super::super::codec::expect_object(entry, path)?,
512                                    path,
513                                )
514                            })?);
515                        }
516                    }
517                    _ => {
518                        return path.with(key, |path| {
519                            Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
520                        });
521                    }
522                }
523            }
524        }
525        Ok(Self {
526            id,
527            extension,
528            value,
529        })
530    }
531}
532
533/// Primitive Type date
534///
535/// A date or partial date (e.g. just year or year + month). There is no time
536/// zone. The format is a union of the schema types gYear, gYearMonth and date.
537/// Dates SHALL be valid dates.
538#[derive(Debug, Clone, Default, PartialEq, Eq)]
539pub struct Date {
540    /// xml:id (or equivalent in JSON)
541    ///
542    /// unique id for the element within a resource (for internal references)
543    pub id: Option<std::string::String>,
544    /// Additional Content defined by implementations
545    ///
546    /// May be used to represent additional information that is not part of the
547    /// basic definition of the resource. In order to make the use of extensions
548    /// safe and manageable, there is a strict set of governance applied to the
549    /// definition and use of extensions. Though any implementer is allowed to
550    /// define an extension, there is a set of requirements that SHALL be met as
551    /// part of the definition of the extension.
552    pub extension: Vec<super::extension::Extension>,
553    /// Primitive value for date
554    ///
555    /// The actual value
556    pub value: Option<std::string::String>,
557}
558impl From<std::string::String> for Date {
559    fn from(value: std::string::String) -> Self {
560        Self {
561            value: Some(value),
562            ..Self::default()
563        }
564    }
565}
566impl From<&str> for Date {
567    fn from(value: &str) -> Self {
568        Self::from(std::string::String::from(value))
569    }
570}
571
572/// The lexical form of the FHIR primitive `date`, anchored to the whole value.
573///
574/// The `regex` extension of `date.value` states it (<https://hl7.org/fhir/STU3/datatypes.html#primitive>),
575/// and the form is an XML Schema pattern, where `\s` is the space, the tab,
576/// the carriage return and the line feed alone (<https://www.w3.org/TR/xmlschema-2/#regexs>).
577#[expect(
578    clippy::expect_used,
579    reason = "the emitter compiles every lexical form it writes, so the pattern holds"
580)]
581static DATE_LEXICAL_FORM: std::sync::LazyLock<regex::bytes::Regex> =
582    std::sync::LazyLock::new(|| {
583        regex::bytes::RegexBuilder::new(
584            r"^(?:-?[0-9]{4}(-(0[1-9]|1[0-2])(-(0[0-9]|[1-2][0-9]|3[0-1]))?)?)$",
585        )
586        .unicode(false)
587        .build()
588        .expect("the lexical form of `date` should compile")
589    });
590
591/// Hands back `text` when it keeps the lexical form of `date`.
592///
593/// # Errors
594///
595/// Returns [`super::super::codec::DecodeErrorKind::BadValue`] at `path` for a value outside the form.
596pub(crate) fn checked_date(
597    text: std::string::String,
598    path: &super::super::codec::Path,
599) -> Result<std::string::String, super::super::codec::DecodeError> {
600    if DATE_LEXICAL_FORM.is_match(text.as_bytes()) {
601        Ok(text)
602    } else {
603        Err(path.error(super::super::codec::DecodeErrorKind::BadValue))
604    }
605}
606
607impl Date {
608    /// Checks `text` against the lexical form of `date`, the one the decoder holds a value to.
609    ///
610    /// # Errors
611    ///
612    /// Returns [`super::super::codec::LexicalError`] naming `date` when `text` is outside the form.
613    pub fn check(text: &str) -> Result<(), super::super::codec::LexicalError> {
614        if DATE_LEXICAL_FORM.is_match(text.as_bytes()) {
615            Ok(())
616        } else {
617            Err(super::super::codec::LexicalError { type_code: "date" })
618        }
619    }
620}
621
622impl super::super::codec::Primitive for Date {
623    fn value_json(
624        &self,
625    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
626        Ok(self
627            .value
628            .as_ref()
629            .map(|v| super::super::codec::Value::String(v.clone())))
630    }
631
632    fn element_json(
633        &self,
634    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
635        if self.id.is_none() && self.extension.is_empty() {
636            return Ok(None);
637        }
638        let mut object = super::super::codec::Object::new();
639        if let Some(id) = &self.id {
640            object.insert(
641                std::string::String::from("id"),
642                super::super::codec::Value::String(id.clone()),
643            );
644        }
645        if !self.extension.is_empty() {
646            let mut items = Vec::with_capacity(self.extension.len());
647            for item in &self.extension {
648                items.push(super::super::codec::Value::Object(
649                    super::super::codec::Json::to_json(item)?,
650                ));
651            }
652            object.insert(
653                std::string::String::from("extension"),
654                super::super::codec::Value::Array(items),
655            );
656        }
657        Ok(Some(super::super::codec::Value::Object(object)))
658    }
659
660    fn has_value(&self) -> bool {
661        self.value.is_some()
662    }
663
664    fn has_element(&self) -> bool {
665        self.id.is_some() || !self.extension.is_empty()
666    }
667
668    fn serialize_value<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
669        match self.value.as_ref() {
670            Some(v) => serde::Serializer::serialize_str(serializer, v),
671            None => serde::Serializer::serialize_none(serializer),
672        }
673    }
674
675    fn serialize_element<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
676        if self.id.is_none() && self.extension.is_empty() {
677            return serde::Serializer::serialize_none(serializer);
678        }
679        let mut map = serde::Serializer::serialize_map(serializer, None)?;
680        if !self.extension.is_empty() {
681            serde::ser::SerializeMap::serialize_entry(&mut map, "extension", &self.extension)?;
682        }
683        if let Some(id) = &self.id {
684            serde::ser::SerializeMap::serialize_entry(&mut map, "id", id)?;
685        }
686        serde::ser::SerializeMap::end(map)
687    }
688
689    fn from_json_parts(
690        value: Option<&super::super::codec::Value>,
691        element: Option<&super::super::codec::Value>,
692        path: &mut super::super::codec::Path,
693    ) -> Result<Self, super::super::codec::DecodeError> {
694        if value.is_none() && element.is_none() && !path.is_lenient() {
695            return Err(path.error(super::super::codec::DecodeErrorKind::MissingProperty));
696        }
697        let value = match value {
698            Some(value) => {
699                let value = super::super::codec::expect_single(value, path)?;
700                Some(checked_date(
701                    super::super::codec::expect_string(value, path)?,
702                    path,
703                )?)
704            }
705            None => None,
706        };
707        let mut id = None;
708        let mut extension = Vec::new();
709        if let Some(element) = element {
710            let object = super::super::codec::expect_object(element, path)?;
711            for (key, item) in object {
712                match key.as_str() {
713                    "id" => {
714                        id =
715                            Some(path.with("id", |path| {
716                                super::super::codec::expect_string(item, path)
717                            })?);
718                    }
719                    "extension" => {
720                        for (index, entry) in super::super::codec::expect_array(item, path)?
721                            .iter()
722                            .enumerate()
723                        {
724                            extension.push(path.with_index("extension", index, |path| {
725                                super::super::codec::Json::from_json(
726                                    super::super::codec::expect_object(entry, path)?,
727                                    path,
728                                )
729                            })?);
730                        }
731                    }
732                    _ => {
733                        return path.with(key, |path| {
734                            Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
735                        });
736                    }
737                }
738            }
739        }
740        Ok(Self {
741            id,
742            extension,
743            value,
744        })
745    }
746}
747
748/// Primitive Type dateTime
749///
750/// A date, date-time or partial date (e.g. just year or year + month). If hours
751/// and minutes are specified, a time zone SHALL be populated. The format is a
752/// union of the schema types gYear, gYearMonth, date and dateTime. Seconds must
753/// be provided due to schema type constraints but may be zero-filled and may be
754/// ignored. Dates SHALL be valid dates.
755#[derive(Debug, Clone, Default, PartialEq, Eq)]
756pub struct DateTime {
757    /// xml:id (or equivalent in JSON)
758    ///
759    /// unique id for the element within a resource (for internal references)
760    pub id: Option<std::string::String>,
761    /// Additional Content defined by implementations
762    ///
763    /// May be used to represent additional information that is not part of the
764    /// basic definition of the resource. In order to make the use of extensions
765    /// safe and manageable, there is a strict set of governance applied to the
766    /// definition and use of extensions. Though any implementer is allowed to
767    /// define an extension, there is a set of requirements that SHALL be met as
768    /// part of the definition of the extension.
769    pub extension: Vec<super::extension::Extension>,
770    /// Primitive value for dateTime
771    ///
772    /// The actual value
773    pub value: Option<std::string::String>,
774}
775impl From<std::string::String> for DateTime {
776    fn from(value: std::string::String) -> Self {
777        Self {
778            value: Some(value),
779            ..Self::default()
780        }
781    }
782}
783impl From<&str> for DateTime {
784    fn from(value: &str) -> Self {
785        Self::from(std::string::String::from(value))
786    }
787}
788
789/// The lexical form of the FHIR primitive `dateTime`, anchored to the whole value.
790///
791/// The `regex` extension of `dateTime.value` states it (<https://hl7.org/fhir/STU3/datatypes.html#primitive>),
792/// and the form is an XML Schema pattern, where `\s` is the space, the tab,
793/// the carriage return and the line feed alone (<https://www.w3.org/TR/xmlschema-2/#regexs>).
794#[expect(
795    clippy::expect_used,
796    reason = "the emitter compiles every lexical form it writes, so the pattern holds"
797)]
798static DATE_TIME_LEXICAL_FORM: std::sync::LazyLock<regex::bytes::Regex> = std::sync::LazyLock::new(
799    || {
800        regex::bytes::RegexBuilder::new(r"^(?:-?([0-9]([0-9]([0-9][1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2][0-9]|3[0-1])(T([01][0-9]|2[0-3]):[0-5][0-9]:([0-5][0-9]|60)(\.[0-9]+)?(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00)))?)?)?)$")
801        .unicode(false)
802        .build()
803        .expect("the lexical form of `dateTime` should compile")
804    },
805);
806
807/// Hands back `text` when it keeps the lexical form of `dateTime`.
808///
809/// # Errors
810///
811/// Returns [`super::super::codec::DecodeErrorKind::BadValue`] at `path` for a value outside the form.
812pub(crate) fn checked_date_time(
813    text: std::string::String,
814    path: &super::super::codec::Path,
815) -> Result<std::string::String, super::super::codec::DecodeError> {
816    if DATE_TIME_LEXICAL_FORM.is_match(text.as_bytes()) {
817        Ok(text)
818    } else {
819        Err(path.error(super::super::codec::DecodeErrorKind::BadValue))
820    }
821}
822
823impl DateTime {
824    /// Checks `text` against the lexical form of `dateTime`, the one the decoder holds a value to.
825    ///
826    /// # Errors
827    ///
828    /// Returns [`super::super::codec::LexicalError`] naming `dateTime` when `text` is outside the form.
829    pub fn check(text: &str) -> Result<(), super::super::codec::LexicalError> {
830        if DATE_TIME_LEXICAL_FORM.is_match(text.as_bytes()) {
831            Ok(())
832        } else {
833            Err(super::super::codec::LexicalError {
834                type_code: "dateTime",
835            })
836        }
837    }
838}
839
840impl super::super::codec::Primitive for DateTime {
841    fn value_json(
842        &self,
843    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
844        Ok(self
845            .value
846            .as_ref()
847            .map(|v| super::super::codec::Value::String(v.clone())))
848    }
849
850    fn element_json(
851        &self,
852    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
853        if self.id.is_none() && self.extension.is_empty() {
854            return Ok(None);
855        }
856        let mut object = super::super::codec::Object::new();
857        if let Some(id) = &self.id {
858            object.insert(
859                std::string::String::from("id"),
860                super::super::codec::Value::String(id.clone()),
861            );
862        }
863        if !self.extension.is_empty() {
864            let mut items = Vec::with_capacity(self.extension.len());
865            for item in &self.extension {
866                items.push(super::super::codec::Value::Object(
867                    super::super::codec::Json::to_json(item)?,
868                ));
869            }
870            object.insert(
871                std::string::String::from("extension"),
872                super::super::codec::Value::Array(items),
873            );
874        }
875        Ok(Some(super::super::codec::Value::Object(object)))
876    }
877
878    fn has_value(&self) -> bool {
879        self.value.is_some()
880    }
881
882    fn has_element(&self) -> bool {
883        self.id.is_some() || !self.extension.is_empty()
884    }
885
886    fn serialize_value<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
887        match self.value.as_ref() {
888            Some(v) => serde::Serializer::serialize_str(serializer, v),
889            None => serde::Serializer::serialize_none(serializer),
890        }
891    }
892
893    fn serialize_element<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
894        if self.id.is_none() && self.extension.is_empty() {
895            return serde::Serializer::serialize_none(serializer);
896        }
897        let mut map = serde::Serializer::serialize_map(serializer, None)?;
898        if !self.extension.is_empty() {
899            serde::ser::SerializeMap::serialize_entry(&mut map, "extension", &self.extension)?;
900        }
901        if let Some(id) = &self.id {
902            serde::ser::SerializeMap::serialize_entry(&mut map, "id", id)?;
903        }
904        serde::ser::SerializeMap::end(map)
905    }
906
907    fn from_json_parts(
908        value: Option<&super::super::codec::Value>,
909        element: Option<&super::super::codec::Value>,
910        path: &mut super::super::codec::Path,
911    ) -> Result<Self, super::super::codec::DecodeError> {
912        if value.is_none() && element.is_none() && !path.is_lenient() {
913            return Err(path.error(super::super::codec::DecodeErrorKind::MissingProperty));
914        }
915        let value = match value {
916            Some(value) => {
917                let value = super::super::codec::expect_single(value, path)?;
918                Some(checked_date_time(
919                    super::super::codec::expect_string(value, path)?,
920                    path,
921                )?)
922            }
923            None => None,
924        };
925        let mut id = None;
926        let mut extension = Vec::new();
927        if let Some(element) = element {
928            let object = super::super::codec::expect_object(element, path)?;
929            for (key, item) in object {
930                match key.as_str() {
931                    "id" => {
932                        id =
933                            Some(path.with("id", |path| {
934                                super::super::codec::expect_string(item, path)
935                            })?);
936                    }
937                    "extension" => {
938                        for (index, entry) in super::super::codec::expect_array(item, path)?
939                            .iter()
940                            .enumerate()
941                        {
942                            extension.push(path.with_index("extension", index, |path| {
943                                super::super::codec::Json::from_json(
944                                    super::super::codec::expect_object(entry, path)?,
945                                    path,
946                                )
947                            })?);
948                        }
949                    }
950                    _ => {
951                        return path.with(key, |path| {
952                            Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
953                        });
954                    }
955                }
956            }
957        }
958        Ok(Self {
959            id,
960            extension,
961            value,
962        })
963    }
964}
965
966/// Primitive Type decimal
967///
968/// A rational number with implicit precision
969#[derive(Debug, Clone, Default, PartialEq, Eq)]
970pub struct Decimal {
971    /// xml:id (or equivalent in JSON)
972    ///
973    /// unique id for the element within a resource (for internal references)
974    pub id: Option<std::string::String>,
975    /// Additional Content defined by implementations
976    ///
977    /// May be used to represent additional information that is not part of the
978    /// basic definition of the resource. In order to make the use of extensions
979    /// safe and manageable, there is a strict set of governance applied to the
980    /// definition and use of extensions. Though any implementer is allowed to
981    /// define an extension, there is a set of requirements that SHALL be met as
982    /// part of the definition of the extension.
983    pub extension: Vec<super::extension::Extension>,
984    /// Primitive value for decimal
985    ///
986    /// The actual value
987    pub value: Option<std::string::String>,
988}
989impl From<std::string::String> for Decimal {
990    fn from(value: std::string::String) -> Self {
991        Self {
992            value: Some(value),
993            ..Self::default()
994        }
995    }
996}
997impl From<&str> for Decimal {
998    fn from(value: &str) -> Self {
999        Self::from(std::string::String::from(value))
1000    }
1001}
1002
1003impl super::super::codec::Primitive for Decimal {
1004    fn value_json(
1005        &self,
1006    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
1007        self.value
1008            .as_ref()
1009            .map(|text| {
1010                text.parse::<super::super::codec::Number>()
1011                    .map(super::super::codec::Value::Number)
1012                    .map_err(|_| super::super::codec::EncodeError::BadDecimal {
1013                        text: text.clone(),
1014                    })
1015            })
1016            .transpose()
1017    }
1018
1019    fn element_json(
1020        &self,
1021    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
1022        if self.id.is_none() && self.extension.is_empty() {
1023            return Ok(None);
1024        }
1025        let mut object = super::super::codec::Object::new();
1026        if let Some(id) = &self.id {
1027            object.insert(
1028                std::string::String::from("id"),
1029                super::super::codec::Value::String(id.clone()),
1030            );
1031        }
1032        if !self.extension.is_empty() {
1033            let mut items = Vec::with_capacity(self.extension.len());
1034            for item in &self.extension {
1035                items.push(super::super::codec::Value::Object(
1036                    super::super::codec::Json::to_json(item)?,
1037                ));
1038            }
1039            object.insert(
1040                std::string::String::from("extension"),
1041                super::super::codec::Value::Array(items),
1042            );
1043        }
1044        Ok(Some(super::super::codec::Value::Object(object)))
1045    }
1046
1047    fn has_value(&self) -> bool {
1048        self.value.is_some()
1049    }
1050
1051    fn has_element(&self) -> bool {
1052        self.id.is_some() || !self.extension.is_empty()
1053    }
1054
1055    fn serialize_value<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1056        match self.value.as_ref() {
1057            Some(text) => serde::Serialize::serialize(
1058                &text.parse::<super::super::codec::Number>().map_err(|_| {
1059                    <S::Error as serde::ser::Error>::custom(
1060                        super::super::codec::EncodeError::BadDecimal { text: text.clone() },
1061                    )
1062                })?,
1063                serializer,
1064            ),
1065            None => serde::Serializer::serialize_none(serializer),
1066        }
1067    }
1068
1069    fn serialize_element<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1070        if self.id.is_none() && self.extension.is_empty() {
1071            return serde::Serializer::serialize_none(serializer);
1072        }
1073        let mut map = serde::Serializer::serialize_map(serializer, None)?;
1074        if !self.extension.is_empty() {
1075            serde::ser::SerializeMap::serialize_entry(&mut map, "extension", &self.extension)?;
1076        }
1077        if let Some(id) = &self.id {
1078            serde::ser::SerializeMap::serialize_entry(&mut map, "id", id)?;
1079        }
1080        serde::ser::SerializeMap::end(map)
1081    }
1082
1083    fn from_json_parts(
1084        value: Option<&super::super::codec::Value>,
1085        element: Option<&super::super::codec::Value>,
1086        path: &mut super::super::codec::Path,
1087    ) -> Result<Self, super::super::codec::DecodeError> {
1088        if value.is_none() && element.is_none() && !path.is_lenient() {
1089            return Err(path.error(super::super::codec::DecodeErrorKind::MissingProperty));
1090        }
1091        let value = match value {
1092            Some(value) => {
1093                let value = super::super::codec::expect_single(value, path)?;
1094                Some(super::super::codec::expect_decimal(value, path)?)
1095            }
1096            None => None,
1097        };
1098        let mut id = None;
1099        let mut extension = Vec::new();
1100        if let Some(element) = element {
1101            let object = super::super::codec::expect_object(element, path)?;
1102            for (key, item) in object {
1103                match key.as_str() {
1104                    "id" => {
1105                        id =
1106                            Some(path.with("id", |path| {
1107                                super::super::codec::expect_string(item, path)
1108                            })?);
1109                    }
1110                    "extension" => {
1111                        for (index, entry) in super::super::codec::expect_array(item, path)?
1112                            .iter()
1113                            .enumerate()
1114                        {
1115                            extension.push(path.with_index("extension", index, |path| {
1116                                super::super::codec::Json::from_json(
1117                                    super::super::codec::expect_object(entry, path)?,
1118                                    path,
1119                                )
1120                            })?);
1121                        }
1122                    }
1123                    _ => {
1124                        return path.with(key, |path| {
1125                            Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
1126                        });
1127                    }
1128                }
1129            }
1130        }
1131        Ok(Self {
1132            id,
1133            extension,
1134            value,
1135        })
1136    }
1137}
1138
1139/// Primitive Type id
1140///
1141/// Any combination of letters, numerals, "-" and ".", with a length limit of 64
1142/// characters. (This might be an integer, an unprefixed OID, UUID or any other
1143/// identifier pattern that meets these constraints.) Ids are case-insensitive.
1144#[derive(Debug, Clone, Default, PartialEq, Eq)]
1145pub struct Id {
1146    /// xml:id (or equivalent in JSON)
1147    ///
1148    /// unique id for the element within a resource (for internal references)
1149    pub id: Option<std::string::String>,
1150    /// Additional Content defined by implementations
1151    ///
1152    /// May be used to represent additional information that is not part of the
1153    /// basic definition of the resource. In order to make the use of extensions
1154    /// safe and manageable, there is a strict set of governance applied to the
1155    /// definition and use of extensions. Though any implementer is allowed to
1156    /// define an extension, there is a set of requirements that SHALL be met as
1157    /// part of the definition of the extension.
1158    pub extension: Vec<super::extension::Extension>,
1159    /// Primitive value for id
1160    pub value: Option<std::string::String>,
1161}
1162impl From<std::string::String> for Id {
1163    fn from(value: std::string::String) -> Self {
1164        Self {
1165            value: Some(value),
1166            ..Self::default()
1167        }
1168    }
1169}
1170impl From<&str> for Id {
1171    fn from(value: &str) -> Self {
1172        Self::from(std::string::String::from(value))
1173    }
1174}
1175
1176/// The lexical form of the FHIR primitive `id`, anchored to the whole value.
1177///
1178/// The `regex` extension of `id.value` states it (<https://hl7.org/fhir/STU3/datatypes.html#primitive>),
1179/// and the form is an XML Schema pattern, where `\s` is the space, the tab,
1180/// the carriage return and the line feed alone (<https://www.w3.org/TR/xmlschema-2/#regexs>).
1181#[expect(
1182    clippy::expect_used,
1183    reason = "the emitter compiles every lexical form it writes, so the pattern holds"
1184)]
1185static ID_LEXICAL_FORM: std::sync::LazyLock<regex::bytes::Regex> = std::sync::LazyLock::new(|| {
1186    regex::bytes::RegexBuilder::new(r"^(?:[A-Za-z0-9\-\.]{1,64})$")
1187        .unicode(false)
1188        .build()
1189        .expect("the lexical form of `id` should compile")
1190});
1191
1192/// Hands back `text` when it keeps the lexical form of `id`.
1193///
1194/// # Errors
1195///
1196/// Returns [`super::super::codec::DecodeErrorKind::BadValue`] at `path` for a value outside the form.
1197pub(crate) fn checked_id(
1198    text: std::string::String,
1199    path: &super::super::codec::Path,
1200) -> Result<std::string::String, super::super::codec::DecodeError> {
1201    if ID_LEXICAL_FORM.is_match(text.as_bytes()) {
1202        Ok(text)
1203    } else {
1204        Err(path.error(super::super::codec::DecodeErrorKind::BadValue))
1205    }
1206}
1207
1208impl Id {
1209    /// Checks `text` against the lexical form of `id`, the one the decoder holds a value to.
1210    ///
1211    /// # Errors
1212    ///
1213    /// Returns [`super::super::codec::LexicalError`] naming `id` when `text` is outside the form.
1214    pub fn check(text: &str) -> Result<(), super::super::codec::LexicalError> {
1215        if ID_LEXICAL_FORM.is_match(text.as_bytes()) {
1216            Ok(())
1217        } else {
1218            Err(super::super::codec::LexicalError { type_code: "id" })
1219        }
1220    }
1221}
1222
1223impl super::super::codec::Primitive for Id {
1224    fn value_json(
1225        &self,
1226    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
1227        Ok(self
1228            .value
1229            .as_ref()
1230            .map(|v| super::super::codec::Value::String(v.clone())))
1231    }
1232
1233    fn element_json(
1234        &self,
1235    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
1236        if self.id.is_none() && self.extension.is_empty() {
1237            return Ok(None);
1238        }
1239        let mut object = super::super::codec::Object::new();
1240        if let Some(id) = &self.id {
1241            object.insert(
1242                std::string::String::from("id"),
1243                super::super::codec::Value::String(id.clone()),
1244            );
1245        }
1246        if !self.extension.is_empty() {
1247            let mut items = Vec::with_capacity(self.extension.len());
1248            for item in &self.extension {
1249                items.push(super::super::codec::Value::Object(
1250                    super::super::codec::Json::to_json(item)?,
1251                ));
1252            }
1253            object.insert(
1254                std::string::String::from("extension"),
1255                super::super::codec::Value::Array(items),
1256            );
1257        }
1258        Ok(Some(super::super::codec::Value::Object(object)))
1259    }
1260
1261    fn has_value(&self) -> bool {
1262        self.value.is_some()
1263    }
1264
1265    fn has_element(&self) -> bool {
1266        self.id.is_some() || !self.extension.is_empty()
1267    }
1268
1269    fn serialize_value<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1270        match self.value.as_ref() {
1271            Some(v) => serde::Serializer::serialize_str(serializer, v),
1272            None => serde::Serializer::serialize_none(serializer),
1273        }
1274    }
1275
1276    fn serialize_element<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1277        if self.id.is_none() && self.extension.is_empty() {
1278            return serde::Serializer::serialize_none(serializer);
1279        }
1280        let mut map = serde::Serializer::serialize_map(serializer, None)?;
1281        if !self.extension.is_empty() {
1282            serde::ser::SerializeMap::serialize_entry(&mut map, "extension", &self.extension)?;
1283        }
1284        if let Some(id) = &self.id {
1285            serde::ser::SerializeMap::serialize_entry(&mut map, "id", id)?;
1286        }
1287        serde::ser::SerializeMap::end(map)
1288    }
1289
1290    fn from_json_parts(
1291        value: Option<&super::super::codec::Value>,
1292        element: Option<&super::super::codec::Value>,
1293        path: &mut super::super::codec::Path,
1294    ) -> Result<Self, super::super::codec::DecodeError> {
1295        if value.is_none() && element.is_none() && !path.is_lenient() {
1296            return Err(path.error(super::super::codec::DecodeErrorKind::MissingProperty));
1297        }
1298        let value = match value {
1299            Some(value) => {
1300                let value = super::super::codec::expect_single(value, path)?;
1301                Some(checked_id(
1302                    super::super::codec::expect_string(value, path)?,
1303                    path,
1304                )?)
1305            }
1306            None => None,
1307        };
1308        let mut id = None;
1309        let mut extension = Vec::new();
1310        if let Some(element) = element {
1311            let object = super::super::codec::expect_object(element, path)?;
1312            for (key, item) in object {
1313                match key.as_str() {
1314                    "id" => {
1315                        id =
1316                            Some(path.with("id", |path| {
1317                                super::super::codec::expect_string(item, path)
1318                            })?);
1319                    }
1320                    "extension" => {
1321                        for (index, entry) in super::super::codec::expect_array(item, path)?
1322                            .iter()
1323                            .enumerate()
1324                        {
1325                            extension.push(path.with_index("extension", index, |path| {
1326                                super::super::codec::Json::from_json(
1327                                    super::super::codec::expect_object(entry, path)?,
1328                                    path,
1329                                )
1330                            })?);
1331                        }
1332                    }
1333                    _ => {
1334                        return path.with(key, |path| {
1335                            Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
1336                        });
1337                    }
1338                }
1339            }
1340        }
1341        Ok(Self {
1342            id,
1343            extension,
1344            value,
1345        })
1346    }
1347}
1348
1349/// Primitive Type instant
1350///
1351/// An instant in time - known at least to the second
1352#[derive(Debug, Clone, Default, PartialEq, Eq)]
1353pub struct Instant {
1354    /// xml:id (or equivalent in JSON)
1355    ///
1356    /// unique id for the element within a resource (for internal references)
1357    pub id: Option<std::string::String>,
1358    /// Additional Content defined by implementations
1359    ///
1360    /// May be used to represent additional information that is not part of the
1361    /// basic definition of the resource. In order to make the use of extensions
1362    /// safe and manageable, there is a strict set of governance applied to the
1363    /// definition and use of extensions. Though any implementer is allowed to
1364    /// define an extension, there is a set of requirements that SHALL be met as
1365    /// part of the definition of the extension.
1366    pub extension: Vec<super::extension::Extension>,
1367    /// Primitive value for instant
1368    ///
1369    /// The actual value
1370    pub value: Option<std::string::String>,
1371}
1372impl From<std::string::String> for Instant {
1373    fn from(value: std::string::String) -> Self {
1374        Self {
1375            value: Some(value),
1376            ..Self::default()
1377        }
1378    }
1379}
1380impl From<&str> for Instant {
1381    fn from(value: &str) -> Self {
1382        Self::from(std::string::String::from(value))
1383    }
1384}
1385
1386/// The lexical form of the FHIR primitive `instant`, anchored to the whole value.
1387///
1388/// The `regex` extension of `instant.value` states it (<https://hl7.org/fhir/STU3/datatypes.html#primitive>),
1389/// and the form is an XML Schema pattern, where `\s` is the space, the tab,
1390/// the carriage return and the line feed alone (<https://www.w3.org/TR/xmlschema-2/#regexs>).
1391#[expect(
1392    clippy::expect_used,
1393    reason = "the emitter compiles every lexical form it writes, so the pattern holds"
1394)]
1395static INSTANT_LEXICAL_FORM: std::sync::LazyLock<regex::bytes::Regex> = std::sync::LazyLock::new(
1396    || {
1397        regex::bytes::RegexBuilder::new(r"^(?:([0-9]([0-9]([0-9][1-9]|[1-9]0)|[1-9]00)|[1-9]000)-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])T([01][0-9]|2[0-3]):[0-5][0-9]:([0-5][0-9]|60)(\.[0-9]+)?(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00)))$")
1398        .unicode(false)
1399        .build()
1400        .expect("the lexical form of `instant` should compile")
1401    },
1402);
1403
1404/// Hands back `text` when it keeps the lexical form of `instant`.
1405///
1406/// # Errors
1407///
1408/// Returns [`super::super::codec::DecodeErrorKind::BadValue`] at `path` for a value outside the form.
1409pub(crate) fn checked_instant(
1410    text: std::string::String,
1411    path: &super::super::codec::Path,
1412) -> Result<std::string::String, super::super::codec::DecodeError> {
1413    if INSTANT_LEXICAL_FORM.is_match(text.as_bytes()) {
1414        Ok(text)
1415    } else {
1416        Err(path.error(super::super::codec::DecodeErrorKind::BadValue))
1417    }
1418}
1419
1420impl Instant {
1421    /// Checks `text` against the lexical form of `instant`, the one the decoder holds a value to.
1422    ///
1423    /// # Errors
1424    ///
1425    /// Returns [`super::super::codec::LexicalError`] naming `instant` when `text` is outside the form.
1426    pub fn check(text: &str) -> Result<(), super::super::codec::LexicalError> {
1427        if INSTANT_LEXICAL_FORM.is_match(text.as_bytes()) {
1428            Ok(())
1429        } else {
1430            Err(super::super::codec::LexicalError {
1431                type_code: "instant",
1432            })
1433        }
1434    }
1435}
1436
1437impl super::super::codec::Primitive for Instant {
1438    fn value_json(
1439        &self,
1440    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
1441        Ok(self
1442            .value
1443            .as_ref()
1444            .map(|v| super::super::codec::Value::String(v.clone())))
1445    }
1446
1447    fn element_json(
1448        &self,
1449    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
1450        if self.id.is_none() && self.extension.is_empty() {
1451            return Ok(None);
1452        }
1453        let mut object = super::super::codec::Object::new();
1454        if let Some(id) = &self.id {
1455            object.insert(
1456                std::string::String::from("id"),
1457                super::super::codec::Value::String(id.clone()),
1458            );
1459        }
1460        if !self.extension.is_empty() {
1461            let mut items = Vec::with_capacity(self.extension.len());
1462            for item in &self.extension {
1463                items.push(super::super::codec::Value::Object(
1464                    super::super::codec::Json::to_json(item)?,
1465                ));
1466            }
1467            object.insert(
1468                std::string::String::from("extension"),
1469                super::super::codec::Value::Array(items),
1470            );
1471        }
1472        Ok(Some(super::super::codec::Value::Object(object)))
1473    }
1474
1475    fn has_value(&self) -> bool {
1476        self.value.is_some()
1477    }
1478
1479    fn has_element(&self) -> bool {
1480        self.id.is_some() || !self.extension.is_empty()
1481    }
1482
1483    fn serialize_value<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1484        match self.value.as_ref() {
1485            Some(v) => serde::Serializer::serialize_str(serializer, v),
1486            None => serde::Serializer::serialize_none(serializer),
1487        }
1488    }
1489
1490    fn serialize_element<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1491        if self.id.is_none() && self.extension.is_empty() {
1492            return serde::Serializer::serialize_none(serializer);
1493        }
1494        let mut map = serde::Serializer::serialize_map(serializer, None)?;
1495        if !self.extension.is_empty() {
1496            serde::ser::SerializeMap::serialize_entry(&mut map, "extension", &self.extension)?;
1497        }
1498        if let Some(id) = &self.id {
1499            serde::ser::SerializeMap::serialize_entry(&mut map, "id", id)?;
1500        }
1501        serde::ser::SerializeMap::end(map)
1502    }
1503
1504    fn from_json_parts(
1505        value: Option<&super::super::codec::Value>,
1506        element: Option<&super::super::codec::Value>,
1507        path: &mut super::super::codec::Path,
1508    ) -> Result<Self, super::super::codec::DecodeError> {
1509        if value.is_none() && element.is_none() && !path.is_lenient() {
1510            return Err(path.error(super::super::codec::DecodeErrorKind::MissingProperty));
1511        }
1512        let value = match value {
1513            Some(value) => {
1514                let value = super::super::codec::expect_single(value, path)?;
1515                Some(checked_instant(
1516                    super::super::codec::expect_string(value, path)?,
1517                    path,
1518                )?)
1519            }
1520            None => None,
1521        };
1522        let mut id = None;
1523        let mut extension = Vec::new();
1524        if let Some(element) = element {
1525            let object = super::super::codec::expect_object(element, path)?;
1526            for (key, item) in object {
1527                match key.as_str() {
1528                    "id" => {
1529                        id =
1530                            Some(path.with("id", |path| {
1531                                super::super::codec::expect_string(item, path)
1532                            })?);
1533                    }
1534                    "extension" => {
1535                        for (index, entry) in super::super::codec::expect_array(item, path)?
1536                            .iter()
1537                            .enumerate()
1538                        {
1539                            extension.push(path.with_index("extension", index, |path| {
1540                                super::super::codec::Json::from_json(
1541                                    super::super::codec::expect_object(entry, path)?,
1542                                    path,
1543                                )
1544                            })?);
1545                        }
1546                    }
1547                    _ => {
1548                        return path.with(key, |path| {
1549                            Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
1550                        });
1551                    }
1552                }
1553            }
1554        }
1555        Ok(Self {
1556            id,
1557            extension,
1558            value,
1559        })
1560    }
1561}
1562
1563/// Primitive Type integer
1564///
1565/// A whole number
1566#[derive(Debug, Clone, Default, PartialEq, Eq)]
1567pub struct Integer {
1568    /// xml:id (or equivalent in JSON)
1569    ///
1570    /// unique id for the element within a resource (for internal references)
1571    pub id: Option<std::string::String>,
1572    /// Additional Content defined by implementations
1573    ///
1574    /// May be used to represent additional information that is not part of the
1575    /// basic definition of the resource. In order to make the use of extensions
1576    /// safe and manageable, there is a strict set of governance applied to the
1577    /// definition and use of extensions. Though any implementer is allowed to
1578    /// define an extension, there is a set of requirements that SHALL be met as
1579    /// part of the definition of the extension.
1580    pub extension: Vec<super::extension::Extension>,
1581    /// Primitive value for integer
1582    ///
1583    /// The actual value
1584    pub value: Option<i32>,
1585}
1586impl From<i32> for Integer {
1587    fn from(value: i32) -> Self {
1588        Self {
1589            value: Some(value),
1590            ..Self::default()
1591        }
1592    }
1593}
1594
1595impl super::super::codec::Primitive for Integer {
1596    fn value_json(
1597        &self,
1598    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
1599        Ok(self
1600            .value
1601            .as_ref()
1602            .map(|v| super::super::codec::Value::from(*v)))
1603    }
1604
1605    fn element_json(
1606        &self,
1607    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
1608        if self.id.is_none() && self.extension.is_empty() {
1609            return Ok(None);
1610        }
1611        let mut object = super::super::codec::Object::new();
1612        if let Some(id) = &self.id {
1613            object.insert(
1614                std::string::String::from("id"),
1615                super::super::codec::Value::String(id.clone()),
1616            );
1617        }
1618        if !self.extension.is_empty() {
1619            let mut items = Vec::with_capacity(self.extension.len());
1620            for item in &self.extension {
1621                items.push(super::super::codec::Value::Object(
1622                    super::super::codec::Json::to_json(item)?,
1623                ));
1624            }
1625            object.insert(
1626                std::string::String::from("extension"),
1627                super::super::codec::Value::Array(items),
1628            );
1629        }
1630        Ok(Some(super::super::codec::Value::Object(object)))
1631    }
1632
1633    fn has_value(&self) -> bool {
1634        self.value.is_some()
1635    }
1636
1637    fn has_element(&self) -> bool {
1638        self.id.is_some() || !self.extension.is_empty()
1639    }
1640
1641    fn serialize_value<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1642        match self.value.as_ref() {
1643            Some(v) => serde::Serializer::serialize_i32(serializer, *v),
1644            None => serde::Serializer::serialize_none(serializer),
1645        }
1646    }
1647
1648    fn serialize_element<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1649        if self.id.is_none() && self.extension.is_empty() {
1650            return serde::Serializer::serialize_none(serializer);
1651        }
1652        let mut map = serde::Serializer::serialize_map(serializer, None)?;
1653        if !self.extension.is_empty() {
1654            serde::ser::SerializeMap::serialize_entry(&mut map, "extension", &self.extension)?;
1655        }
1656        if let Some(id) = &self.id {
1657            serde::ser::SerializeMap::serialize_entry(&mut map, "id", id)?;
1658        }
1659        serde::ser::SerializeMap::end(map)
1660    }
1661
1662    fn from_json_parts(
1663        value: Option<&super::super::codec::Value>,
1664        element: Option<&super::super::codec::Value>,
1665        path: &mut super::super::codec::Path,
1666    ) -> Result<Self, super::super::codec::DecodeError> {
1667        if value.is_none() && element.is_none() && !path.is_lenient() {
1668            return Err(path.error(super::super::codec::DecodeErrorKind::MissingProperty));
1669        }
1670        let value = match value {
1671            Some(value) => {
1672                let value = super::super::codec::expect_single(value, path)?;
1673                Some(super::super::codec::expect_i32(value, path)?)
1674            }
1675            None => None,
1676        };
1677        let mut id = None;
1678        let mut extension = Vec::new();
1679        if let Some(element) = element {
1680            let object = super::super::codec::expect_object(element, path)?;
1681            for (key, item) in object {
1682                match key.as_str() {
1683                    "id" => {
1684                        id =
1685                            Some(path.with("id", |path| {
1686                                super::super::codec::expect_string(item, path)
1687                            })?);
1688                    }
1689                    "extension" => {
1690                        for (index, entry) in super::super::codec::expect_array(item, path)?
1691                            .iter()
1692                            .enumerate()
1693                        {
1694                            extension.push(path.with_index("extension", index, |path| {
1695                                super::super::codec::Json::from_json(
1696                                    super::super::codec::expect_object(entry, path)?,
1697                                    path,
1698                                )
1699                            })?);
1700                        }
1701                    }
1702                    _ => {
1703                        return path.with(key, |path| {
1704                            Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
1705                        });
1706                    }
1707                }
1708            }
1709        }
1710        Ok(Self {
1711            id,
1712            extension,
1713            value,
1714        })
1715    }
1716}
1717
1718/// Primitive Type markdown
1719///
1720/// A string that may contain markdown syntax for optional processing by a mark
1721/// down presentation engine
1722#[derive(Debug, Clone, Default, PartialEq, Eq)]
1723pub struct Markdown {
1724    /// xml:id (or equivalent in JSON)
1725    ///
1726    /// unique id for the element within a resource (for internal references)
1727    pub id: Option<std::string::String>,
1728    /// Additional Content defined by implementations
1729    ///
1730    /// May be used to represent additional information that is not part of the
1731    /// basic definition of the resource. In order to make the use of extensions
1732    /// safe and manageable, there is a strict set of governance applied to the
1733    /// definition and use of extensions. Though any implementer is allowed to
1734    /// define an extension, there is a set of requirements that SHALL be met as
1735    /// part of the definition of the extension.
1736    pub extension: Vec<super::extension::Extension>,
1737    /// Primitive value for markdown
1738    pub value: Option<std::string::String>,
1739}
1740impl From<std::string::String> for Markdown {
1741    fn from(value: std::string::String) -> Self {
1742        Self {
1743            value: Some(value),
1744            ..Self::default()
1745        }
1746    }
1747}
1748impl From<&str> for Markdown {
1749    fn from(value: &str) -> Self {
1750        Self::from(std::string::String::from(value))
1751    }
1752}
1753
1754impl super::super::codec::Primitive for Markdown {
1755    fn value_json(
1756        &self,
1757    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
1758        Ok(self
1759            .value
1760            .as_ref()
1761            .map(|v| super::super::codec::Value::String(v.clone())))
1762    }
1763
1764    fn element_json(
1765        &self,
1766    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
1767        if self.id.is_none() && self.extension.is_empty() {
1768            return Ok(None);
1769        }
1770        let mut object = super::super::codec::Object::new();
1771        if let Some(id) = &self.id {
1772            object.insert(
1773                std::string::String::from("id"),
1774                super::super::codec::Value::String(id.clone()),
1775            );
1776        }
1777        if !self.extension.is_empty() {
1778            let mut items = Vec::with_capacity(self.extension.len());
1779            for item in &self.extension {
1780                items.push(super::super::codec::Value::Object(
1781                    super::super::codec::Json::to_json(item)?,
1782                ));
1783            }
1784            object.insert(
1785                std::string::String::from("extension"),
1786                super::super::codec::Value::Array(items),
1787            );
1788        }
1789        Ok(Some(super::super::codec::Value::Object(object)))
1790    }
1791
1792    fn has_value(&self) -> bool {
1793        self.value.is_some()
1794    }
1795
1796    fn has_element(&self) -> bool {
1797        self.id.is_some() || !self.extension.is_empty()
1798    }
1799
1800    fn serialize_value<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1801        match self.value.as_ref() {
1802            Some(v) => serde::Serializer::serialize_str(serializer, v),
1803            None => serde::Serializer::serialize_none(serializer),
1804        }
1805    }
1806
1807    fn serialize_element<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1808        if self.id.is_none() && self.extension.is_empty() {
1809            return serde::Serializer::serialize_none(serializer);
1810        }
1811        let mut map = serde::Serializer::serialize_map(serializer, None)?;
1812        if !self.extension.is_empty() {
1813            serde::ser::SerializeMap::serialize_entry(&mut map, "extension", &self.extension)?;
1814        }
1815        if let Some(id) = &self.id {
1816            serde::ser::SerializeMap::serialize_entry(&mut map, "id", id)?;
1817        }
1818        serde::ser::SerializeMap::end(map)
1819    }
1820
1821    fn from_json_parts(
1822        value: Option<&super::super::codec::Value>,
1823        element: Option<&super::super::codec::Value>,
1824        path: &mut super::super::codec::Path,
1825    ) -> Result<Self, super::super::codec::DecodeError> {
1826        if value.is_none() && element.is_none() && !path.is_lenient() {
1827            return Err(path.error(super::super::codec::DecodeErrorKind::MissingProperty));
1828        }
1829        let value = match value {
1830            Some(value) => {
1831                let value = super::super::codec::expect_single(value, path)?;
1832                Some(super::super::codec::expect_string(value, path)?)
1833            }
1834            None => None,
1835        };
1836        let mut id = None;
1837        let mut extension = Vec::new();
1838        if let Some(element) = element {
1839            let object = super::super::codec::expect_object(element, path)?;
1840            for (key, item) in object {
1841                match key.as_str() {
1842                    "id" => {
1843                        id =
1844                            Some(path.with("id", |path| {
1845                                super::super::codec::expect_string(item, path)
1846                            })?);
1847                    }
1848                    "extension" => {
1849                        for (index, entry) in super::super::codec::expect_array(item, path)?
1850                            .iter()
1851                            .enumerate()
1852                        {
1853                            extension.push(path.with_index("extension", index, |path| {
1854                                super::super::codec::Json::from_json(
1855                                    super::super::codec::expect_object(entry, path)?,
1856                                    path,
1857                                )
1858                            })?);
1859                        }
1860                    }
1861                    _ => {
1862                        return path.with(key, |path| {
1863                            Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
1864                        });
1865                    }
1866                }
1867            }
1868        }
1869        Ok(Self {
1870            id,
1871            extension,
1872            value,
1873        })
1874    }
1875}
1876
1877/// Primitive Type oid
1878///
1879/// An OID represented as a URI
1880#[derive(Debug, Clone, Default, PartialEq, Eq)]
1881pub struct Oid {
1882    /// xml:id (or equivalent in JSON)
1883    ///
1884    /// unique id for the element within a resource (for internal references)
1885    pub id: Option<std::string::String>,
1886    /// Additional Content defined by implementations
1887    ///
1888    /// May be used to represent additional information that is not part of the
1889    /// basic definition of the resource. In order to make the use of extensions
1890    /// safe and manageable, there is a strict set of governance applied to the
1891    /// definition and use of extensions. Though any implementer is allowed to
1892    /// define an extension, there is a set of requirements that SHALL be met as
1893    /// part of the definition of the extension.
1894    pub extension: Vec<super::extension::Extension>,
1895    /// Primitive value for oid
1896    pub value: Option<std::string::String>,
1897}
1898impl From<std::string::String> for Oid {
1899    fn from(value: std::string::String) -> Self {
1900        Self {
1901            value: Some(value),
1902            ..Self::default()
1903        }
1904    }
1905}
1906impl From<&str> for Oid {
1907    fn from(value: &str) -> Self {
1908        Self::from(std::string::String::from(value))
1909    }
1910}
1911
1912/// The lexical form of the FHIR primitive `oid`, anchored to the whole value.
1913///
1914/// The `regex` extension of `oid.value` states it (<https://hl7.org/fhir/STU3/datatypes.html#primitive>),
1915/// and the form is an XML Schema pattern, where `\s` is the space, the tab,
1916/// the carriage return and the line feed alone (<https://www.w3.org/TR/xmlschema-2/#regexs>).
1917#[expect(
1918    clippy::expect_used,
1919    reason = "the emitter compiles every lexical form it writes, so the pattern holds"
1920)]
1921static OID_LEXICAL_FORM: std::sync::LazyLock<regex::bytes::Regex> =
1922    std::sync::LazyLock::new(|| {
1923        regex::bytes::RegexBuilder::new(r"^(?:urn:oid:(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))*)$")
1924            .unicode(false)
1925            .build()
1926            .expect("the lexical form of `oid` should compile")
1927    });
1928
1929/// Hands back `text` when it keeps the lexical form of `oid`.
1930///
1931/// # Errors
1932///
1933/// Returns [`super::super::codec::DecodeErrorKind::BadValue`] at `path` for a value outside the form.
1934pub(crate) fn checked_oid(
1935    text: std::string::String,
1936    path: &super::super::codec::Path,
1937) -> Result<std::string::String, super::super::codec::DecodeError> {
1938    if OID_LEXICAL_FORM.is_match(text.as_bytes()) {
1939        Ok(text)
1940    } else {
1941        Err(path.error(super::super::codec::DecodeErrorKind::BadValue))
1942    }
1943}
1944
1945impl Oid {
1946    /// Checks `text` against the lexical form of `oid`, the one the decoder holds a value to.
1947    ///
1948    /// # Errors
1949    ///
1950    /// Returns [`super::super::codec::LexicalError`] naming `oid` when `text` is outside the form.
1951    pub fn check(text: &str) -> Result<(), super::super::codec::LexicalError> {
1952        if OID_LEXICAL_FORM.is_match(text.as_bytes()) {
1953            Ok(())
1954        } else {
1955            Err(super::super::codec::LexicalError { type_code: "oid" })
1956        }
1957    }
1958}
1959
1960impl super::super::codec::Primitive for Oid {
1961    fn value_json(
1962        &self,
1963    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
1964        Ok(self
1965            .value
1966            .as_ref()
1967            .map(|v| super::super::codec::Value::String(v.clone())))
1968    }
1969
1970    fn element_json(
1971        &self,
1972    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
1973        if self.id.is_none() && self.extension.is_empty() {
1974            return Ok(None);
1975        }
1976        let mut object = super::super::codec::Object::new();
1977        if let Some(id) = &self.id {
1978            object.insert(
1979                std::string::String::from("id"),
1980                super::super::codec::Value::String(id.clone()),
1981            );
1982        }
1983        if !self.extension.is_empty() {
1984            let mut items = Vec::with_capacity(self.extension.len());
1985            for item in &self.extension {
1986                items.push(super::super::codec::Value::Object(
1987                    super::super::codec::Json::to_json(item)?,
1988                ));
1989            }
1990            object.insert(
1991                std::string::String::from("extension"),
1992                super::super::codec::Value::Array(items),
1993            );
1994        }
1995        Ok(Some(super::super::codec::Value::Object(object)))
1996    }
1997
1998    fn has_value(&self) -> bool {
1999        self.value.is_some()
2000    }
2001
2002    fn has_element(&self) -> bool {
2003        self.id.is_some() || !self.extension.is_empty()
2004    }
2005
2006    fn serialize_value<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2007        match self.value.as_ref() {
2008            Some(v) => serde::Serializer::serialize_str(serializer, v),
2009            None => serde::Serializer::serialize_none(serializer),
2010        }
2011    }
2012
2013    fn serialize_element<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2014        if self.id.is_none() && self.extension.is_empty() {
2015            return serde::Serializer::serialize_none(serializer);
2016        }
2017        let mut map = serde::Serializer::serialize_map(serializer, None)?;
2018        if !self.extension.is_empty() {
2019            serde::ser::SerializeMap::serialize_entry(&mut map, "extension", &self.extension)?;
2020        }
2021        if let Some(id) = &self.id {
2022            serde::ser::SerializeMap::serialize_entry(&mut map, "id", id)?;
2023        }
2024        serde::ser::SerializeMap::end(map)
2025    }
2026
2027    fn from_json_parts(
2028        value: Option<&super::super::codec::Value>,
2029        element: Option<&super::super::codec::Value>,
2030        path: &mut super::super::codec::Path,
2031    ) -> Result<Self, super::super::codec::DecodeError> {
2032        if value.is_none() && element.is_none() && !path.is_lenient() {
2033            return Err(path.error(super::super::codec::DecodeErrorKind::MissingProperty));
2034        }
2035        let value = match value {
2036            Some(value) => {
2037                let value = super::super::codec::expect_single(value, path)?;
2038                Some(checked_oid(
2039                    super::super::codec::expect_string(value, path)?,
2040                    path,
2041                )?)
2042            }
2043            None => None,
2044        };
2045        let mut id = None;
2046        let mut extension = Vec::new();
2047        if let Some(element) = element {
2048            let object = super::super::codec::expect_object(element, path)?;
2049            for (key, item) in object {
2050                match key.as_str() {
2051                    "id" => {
2052                        id =
2053                            Some(path.with("id", |path| {
2054                                super::super::codec::expect_string(item, path)
2055                            })?);
2056                    }
2057                    "extension" => {
2058                        for (index, entry) in super::super::codec::expect_array(item, path)?
2059                            .iter()
2060                            .enumerate()
2061                        {
2062                            extension.push(path.with_index("extension", index, |path| {
2063                                super::super::codec::Json::from_json(
2064                                    super::super::codec::expect_object(entry, path)?,
2065                                    path,
2066                                )
2067                            })?);
2068                        }
2069                    }
2070                    _ => {
2071                        return path.with(key, |path| {
2072                            Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
2073                        });
2074                    }
2075                }
2076            }
2077        }
2078        Ok(Self {
2079            id,
2080            extension,
2081            value,
2082        })
2083    }
2084}
2085
2086/// Primitive Type positiveInt
2087///
2088/// An integer with a value that is positive (e.g. \>0)
2089#[derive(Debug, Clone, Default, PartialEq, Eq)]
2090pub struct PositiveInt {
2091    /// xml:id (or equivalent in JSON)
2092    ///
2093    /// unique id for the element within a resource (for internal references)
2094    pub id: Option<std::string::String>,
2095    /// Additional Content defined by implementations
2096    ///
2097    /// May be used to represent additional information that is not part of the
2098    /// basic definition of the resource. In order to make the use of extensions
2099    /// safe and manageable, there is a strict set of governance applied to the
2100    /// definition and use of extensions. Though any implementer is allowed to
2101    /// define an extension, there is a set of requirements that SHALL be met as
2102    /// part of the definition of the extension.
2103    pub extension: Vec<super::extension::Extension>,
2104    /// Primitive value for positiveInt
2105    pub value: Option<u32>,
2106}
2107impl From<u32> for PositiveInt {
2108    fn from(value: u32) -> Self {
2109        Self {
2110            value: Some(value),
2111            ..Self::default()
2112        }
2113    }
2114}
2115
2116impl super::super::codec::Primitive for PositiveInt {
2117    fn value_json(
2118        &self,
2119    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
2120        Ok(self
2121            .value
2122            .as_ref()
2123            .map(|v| super::super::codec::Value::from(*v)))
2124    }
2125
2126    fn element_json(
2127        &self,
2128    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
2129        if self.id.is_none() && self.extension.is_empty() {
2130            return Ok(None);
2131        }
2132        let mut object = super::super::codec::Object::new();
2133        if let Some(id) = &self.id {
2134            object.insert(
2135                std::string::String::from("id"),
2136                super::super::codec::Value::String(id.clone()),
2137            );
2138        }
2139        if !self.extension.is_empty() {
2140            let mut items = Vec::with_capacity(self.extension.len());
2141            for item in &self.extension {
2142                items.push(super::super::codec::Value::Object(
2143                    super::super::codec::Json::to_json(item)?,
2144                ));
2145            }
2146            object.insert(
2147                std::string::String::from("extension"),
2148                super::super::codec::Value::Array(items),
2149            );
2150        }
2151        Ok(Some(super::super::codec::Value::Object(object)))
2152    }
2153
2154    fn has_value(&self) -> bool {
2155        self.value.is_some()
2156    }
2157
2158    fn has_element(&self) -> bool {
2159        self.id.is_some() || !self.extension.is_empty()
2160    }
2161
2162    fn serialize_value<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2163        match self.value.as_ref() {
2164            Some(v) => serde::Serializer::serialize_u32(serializer, *v),
2165            None => serde::Serializer::serialize_none(serializer),
2166        }
2167    }
2168
2169    fn serialize_element<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2170        if self.id.is_none() && self.extension.is_empty() {
2171            return serde::Serializer::serialize_none(serializer);
2172        }
2173        let mut map = serde::Serializer::serialize_map(serializer, None)?;
2174        if !self.extension.is_empty() {
2175            serde::ser::SerializeMap::serialize_entry(&mut map, "extension", &self.extension)?;
2176        }
2177        if let Some(id) = &self.id {
2178            serde::ser::SerializeMap::serialize_entry(&mut map, "id", id)?;
2179        }
2180        serde::ser::SerializeMap::end(map)
2181    }
2182
2183    fn from_json_parts(
2184        value: Option<&super::super::codec::Value>,
2185        element: Option<&super::super::codec::Value>,
2186        path: &mut super::super::codec::Path,
2187    ) -> Result<Self, super::super::codec::DecodeError> {
2188        if value.is_none() && element.is_none() && !path.is_lenient() {
2189            return Err(path.error(super::super::codec::DecodeErrorKind::MissingProperty));
2190        }
2191        let value = match value {
2192            Some(value) => {
2193                let value = super::super::codec::expect_single(value, path)?;
2194                Some(super::super::codec::expect_u32(value, 1, path)?)
2195            }
2196            None => None,
2197        };
2198        let mut id = None;
2199        let mut extension = Vec::new();
2200        if let Some(element) = element {
2201            let object = super::super::codec::expect_object(element, path)?;
2202            for (key, item) in object {
2203                match key.as_str() {
2204                    "id" => {
2205                        id =
2206                            Some(path.with("id", |path| {
2207                                super::super::codec::expect_string(item, path)
2208                            })?);
2209                    }
2210                    "extension" => {
2211                        for (index, entry) in super::super::codec::expect_array(item, path)?
2212                            .iter()
2213                            .enumerate()
2214                        {
2215                            extension.push(path.with_index("extension", index, |path| {
2216                                super::super::codec::Json::from_json(
2217                                    super::super::codec::expect_object(entry, path)?,
2218                                    path,
2219                                )
2220                            })?);
2221                        }
2222                    }
2223                    _ => {
2224                        return path.with(key, |path| {
2225                            Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
2226                        });
2227                    }
2228                }
2229            }
2230        }
2231        Ok(Self {
2232            id,
2233            extension,
2234            value,
2235        })
2236    }
2237}
2238
2239/// Primitive Type string
2240///
2241/// A sequence of Unicode characters
2242#[derive(Debug, Clone, Default, PartialEq, Eq)]
2243pub struct String {
2244    /// xml:id (or equivalent in JSON)
2245    ///
2246    /// unique id for the element within a resource (for internal references)
2247    pub id: Option<std::string::String>,
2248    /// Additional Content defined by implementations
2249    ///
2250    /// May be used to represent additional information that is not part of the
2251    /// basic definition of the resource. In order to make the use of extensions
2252    /// safe and manageable, there is a strict set of governance applied to the
2253    /// definition and use of extensions. Though any implementer is allowed to
2254    /// define an extension, there is a set of requirements that SHALL be met as
2255    /// part of the definition of the extension.
2256    pub extension: Vec<super::extension::Extension>,
2257    /// Primitive value for string
2258    ///
2259    /// The actual value
2260    pub value: Option<std::string::String>,
2261}
2262impl From<std::string::String> for String {
2263    fn from(value: std::string::String) -> Self {
2264        Self {
2265            value: Some(value),
2266            ..Self::default()
2267        }
2268    }
2269}
2270impl From<&str> for String {
2271    fn from(value: &str) -> Self {
2272        Self::from(std::string::String::from(value))
2273    }
2274}
2275
2276impl super::super::codec::Primitive for String {
2277    fn value_json(
2278        &self,
2279    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
2280        Ok(self
2281            .value
2282            .as_ref()
2283            .map(|v| super::super::codec::Value::String(v.clone())))
2284    }
2285
2286    fn element_json(
2287        &self,
2288    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
2289        if self.id.is_none() && self.extension.is_empty() {
2290            return Ok(None);
2291        }
2292        let mut object = super::super::codec::Object::new();
2293        if let Some(id) = &self.id {
2294            object.insert(
2295                std::string::String::from("id"),
2296                super::super::codec::Value::String(id.clone()),
2297            );
2298        }
2299        if !self.extension.is_empty() {
2300            let mut items = Vec::with_capacity(self.extension.len());
2301            for item in &self.extension {
2302                items.push(super::super::codec::Value::Object(
2303                    super::super::codec::Json::to_json(item)?,
2304                ));
2305            }
2306            object.insert(
2307                std::string::String::from("extension"),
2308                super::super::codec::Value::Array(items),
2309            );
2310        }
2311        Ok(Some(super::super::codec::Value::Object(object)))
2312    }
2313
2314    fn has_value(&self) -> bool {
2315        self.value.is_some()
2316    }
2317
2318    fn has_element(&self) -> bool {
2319        self.id.is_some() || !self.extension.is_empty()
2320    }
2321
2322    fn serialize_value<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2323        match self.value.as_ref() {
2324            Some(v) => serde::Serializer::serialize_str(serializer, v),
2325            None => serde::Serializer::serialize_none(serializer),
2326        }
2327    }
2328
2329    fn serialize_element<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2330        if self.id.is_none() && self.extension.is_empty() {
2331            return serde::Serializer::serialize_none(serializer);
2332        }
2333        let mut map = serde::Serializer::serialize_map(serializer, None)?;
2334        if !self.extension.is_empty() {
2335            serde::ser::SerializeMap::serialize_entry(&mut map, "extension", &self.extension)?;
2336        }
2337        if let Some(id) = &self.id {
2338            serde::ser::SerializeMap::serialize_entry(&mut map, "id", id)?;
2339        }
2340        serde::ser::SerializeMap::end(map)
2341    }
2342
2343    fn from_json_parts(
2344        value: Option<&super::super::codec::Value>,
2345        element: Option<&super::super::codec::Value>,
2346        path: &mut super::super::codec::Path,
2347    ) -> Result<Self, super::super::codec::DecodeError> {
2348        if value.is_none() && element.is_none() && !path.is_lenient() {
2349            return Err(path.error(super::super::codec::DecodeErrorKind::MissingProperty));
2350        }
2351        let value = match value {
2352            Some(value) => {
2353                let value = super::super::codec::expect_single(value, path)?;
2354                Some(super::super::codec::expect_string(value, path)?)
2355            }
2356            None => None,
2357        };
2358        let mut id = None;
2359        let mut extension = Vec::new();
2360        if let Some(element) = element {
2361            let object = super::super::codec::expect_object(element, path)?;
2362            for (key, item) in object {
2363                match key.as_str() {
2364                    "id" => {
2365                        id =
2366                            Some(path.with("id", |path| {
2367                                super::super::codec::expect_string(item, path)
2368                            })?);
2369                    }
2370                    "extension" => {
2371                        for (index, entry) in super::super::codec::expect_array(item, path)?
2372                            .iter()
2373                            .enumerate()
2374                        {
2375                            extension.push(path.with_index("extension", index, |path| {
2376                                super::super::codec::Json::from_json(
2377                                    super::super::codec::expect_object(entry, path)?,
2378                                    path,
2379                                )
2380                            })?);
2381                        }
2382                    }
2383                    _ => {
2384                        return path.with(key, |path| {
2385                            Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
2386                        });
2387                    }
2388                }
2389            }
2390        }
2391        Ok(Self {
2392            id,
2393            extension,
2394            value,
2395        })
2396    }
2397}
2398
2399/// Primitive Type time
2400///
2401/// A time during the day, with no date specified
2402#[derive(Debug, Clone, Default, PartialEq, Eq)]
2403pub struct Time {
2404    /// xml:id (or equivalent in JSON)
2405    ///
2406    /// unique id for the element within a resource (for internal references)
2407    pub id: Option<std::string::String>,
2408    /// Additional Content defined by implementations
2409    ///
2410    /// May be used to represent additional information that is not part of the
2411    /// basic definition of the resource. In order to make the use of extensions
2412    /// safe and manageable, there is a strict set of governance applied to the
2413    /// definition and use of extensions. Though any implementer is allowed to
2414    /// define an extension, there is a set of requirements that SHALL be met as
2415    /// part of the definition of the extension.
2416    pub extension: Vec<super::extension::Extension>,
2417    /// Primitive value for time
2418    ///
2419    /// The actual value
2420    pub value: Option<std::string::String>,
2421}
2422impl From<std::string::String> for Time {
2423    fn from(value: std::string::String) -> Self {
2424        Self {
2425            value: Some(value),
2426            ..Self::default()
2427        }
2428    }
2429}
2430impl From<&str> for Time {
2431    fn from(value: &str) -> Self {
2432        Self::from(std::string::String::from(value))
2433    }
2434}
2435
2436/// The lexical form of the FHIR primitive `time`, anchored to the whole value.
2437///
2438/// The `regex` extension of `time.value` states it (<https://hl7.org/fhir/STU3/datatypes.html#primitive>),
2439/// and the form is an XML Schema pattern, where `\s` is the space, the tab,
2440/// the carriage return and the line feed alone (<https://www.w3.org/TR/xmlschema-2/#regexs>).
2441#[expect(
2442    clippy::expect_used,
2443    reason = "the emitter compiles every lexical form it writes, so the pattern holds"
2444)]
2445static TIME_LEXICAL_FORM: std::sync::LazyLock<regex::bytes::Regex> =
2446    std::sync::LazyLock::new(|| {
2447        regex::bytes::RegexBuilder::new(
2448            r"^(?:([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?)$",
2449        )
2450        .unicode(false)
2451        .build()
2452        .expect("the lexical form of `time` should compile")
2453    });
2454
2455/// Hands back `text` when it keeps the lexical form of `time`.
2456///
2457/// # Errors
2458///
2459/// Returns [`super::super::codec::DecodeErrorKind::BadValue`] at `path` for a value outside the form.
2460pub(crate) fn checked_time(
2461    text: std::string::String,
2462    path: &super::super::codec::Path,
2463) -> Result<std::string::String, super::super::codec::DecodeError> {
2464    if TIME_LEXICAL_FORM.is_match(text.as_bytes()) {
2465        Ok(text)
2466    } else {
2467        Err(path.error(super::super::codec::DecodeErrorKind::BadValue))
2468    }
2469}
2470
2471impl Time {
2472    /// Checks `text` against the lexical form of `time`, the one the decoder holds a value to.
2473    ///
2474    /// # Errors
2475    ///
2476    /// Returns [`super::super::codec::LexicalError`] naming `time` when `text` is outside the form.
2477    pub fn check(text: &str) -> Result<(), super::super::codec::LexicalError> {
2478        if TIME_LEXICAL_FORM.is_match(text.as_bytes()) {
2479            Ok(())
2480        } else {
2481            Err(super::super::codec::LexicalError { type_code: "time" })
2482        }
2483    }
2484}
2485
2486impl super::super::codec::Primitive for Time {
2487    fn value_json(
2488        &self,
2489    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
2490        Ok(self
2491            .value
2492            .as_ref()
2493            .map(|v| super::super::codec::Value::String(v.clone())))
2494    }
2495
2496    fn element_json(
2497        &self,
2498    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
2499        if self.id.is_none() && self.extension.is_empty() {
2500            return Ok(None);
2501        }
2502        let mut object = super::super::codec::Object::new();
2503        if let Some(id) = &self.id {
2504            object.insert(
2505                std::string::String::from("id"),
2506                super::super::codec::Value::String(id.clone()),
2507            );
2508        }
2509        if !self.extension.is_empty() {
2510            let mut items = Vec::with_capacity(self.extension.len());
2511            for item in &self.extension {
2512                items.push(super::super::codec::Value::Object(
2513                    super::super::codec::Json::to_json(item)?,
2514                ));
2515            }
2516            object.insert(
2517                std::string::String::from("extension"),
2518                super::super::codec::Value::Array(items),
2519            );
2520        }
2521        Ok(Some(super::super::codec::Value::Object(object)))
2522    }
2523
2524    fn has_value(&self) -> bool {
2525        self.value.is_some()
2526    }
2527
2528    fn has_element(&self) -> bool {
2529        self.id.is_some() || !self.extension.is_empty()
2530    }
2531
2532    fn serialize_value<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2533        match self.value.as_ref() {
2534            Some(v) => serde::Serializer::serialize_str(serializer, v),
2535            None => serde::Serializer::serialize_none(serializer),
2536        }
2537    }
2538
2539    fn serialize_element<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2540        if self.id.is_none() && self.extension.is_empty() {
2541            return serde::Serializer::serialize_none(serializer);
2542        }
2543        let mut map = serde::Serializer::serialize_map(serializer, None)?;
2544        if !self.extension.is_empty() {
2545            serde::ser::SerializeMap::serialize_entry(&mut map, "extension", &self.extension)?;
2546        }
2547        if let Some(id) = &self.id {
2548            serde::ser::SerializeMap::serialize_entry(&mut map, "id", id)?;
2549        }
2550        serde::ser::SerializeMap::end(map)
2551    }
2552
2553    fn from_json_parts(
2554        value: Option<&super::super::codec::Value>,
2555        element: Option<&super::super::codec::Value>,
2556        path: &mut super::super::codec::Path,
2557    ) -> Result<Self, super::super::codec::DecodeError> {
2558        if value.is_none() && element.is_none() && !path.is_lenient() {
2559            return Err(path.error(super::super::codec::DecodeErrorKind::MissingProperty));
2560        }
2561        let value = match value {
2562            Some(value) => {
2563                let value = super::super::codec::expect_single(value, path)?;
2564                Some(checked_time(
2565                    super::super::codec::expect_string(value, path)?,
2566                    path,
2567                )?)
2568            }
2569            None => None,
2570        };
2571        let mut id = None;
2572        let mut extension = Vec::new();
2573        if let Some(element) = element {
2574            let object = super::super::codec::expect_object(element, path)?;
2575            for (key, item) in object {
2576                match key.as_str() {
2577                    "id" => {
2578                        id =
2579                            Some(path.with("id", |path| {
2580                                super::super::codec::expect_string(item, path)
2581                            })?);
2582                    }
2583                    "extension" => {
2584                        for (index, entry) in super::super::codec::expect_array(item, path)?
2585                            .iter()
2586                            .enumerate()
2587                        {
2588                            extension.push(path.with_index("extension", index, |path| {
2589                                super::super::codec::Json::from_json(
2590                                    super::super::codec::expect_object(entry, path)?,
2591                                    path,
2592                                )
2593                            })?);
2594                        }
2595                    }
2596                    _ => {
2597                        return path.with(key, |path| {
2598                            Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
2599                        });
2600                    }
2601                }
2602            }
2603        }
2604        Ok(Self {
2605            id,
2606            extension,
2607            value,
2608        })
2609    }
2610}
2611
2612/// Primitive Type unsignedInt
2613///
2614/// An integer with a value that is not negative (e.g. \>= 0)
2615#[derive(Debug, Clone, Default, PartialEq, Eq)]
2616pub struct UnsignedInt {
2617    /// xml:id (or equivalent in JSON)
2618    ///
2619    /// unique id for the element within a resource (for internal references)
2620    pub id: Option<std::string::String>,
2621    /// Additional Content defined by implementations
2622    ///
2623    /// May be used to represent additional information that is not part of the
2624    /// basic definition of the resource. In order to make the use of extensions
2625    /// safe and manageable, there is a strict set of governance applied to the
2626    /// definition and use of extensions. Though any implementer is allowed to
2627    /// define an extension, there is a set of requirements that SHALL be met as
2628    /// part of the definition of the extension.
2629    pub extension: Vec<super::extension::Extension>,
2630    /// Primitive value for unsignedInt
2631    pub value: Option<u32>,
2632}
2633impl From<u32> for UnsignedInt {
2634    fn from(value: u32) -> Self {
2635        Self {
2636            value: Some(value),
2637            ..Self::default()
2638        }
2639    }
2640}
2641
2642impl super::super::codec::Primitive for UnsignedInt {
2643    fn value_json(
2644        &self,
2645    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
2646        Ok(self
2647            .value
2648            .as_ref()
2649            .map(|v| super::super::codec::Value::from(*v)))
2650    }
2651
2652    fn element_json(
2653        &self,
2654    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
2655        if self.id.is_none() && self.extension.is_empty() {
2656            return Ok(None);
2657        }
2658        let mut object = super::super::codec::Object::new();
2659        if let Some(id) = &self.id {
2660            object.insert(
2661                std::string::String::from("id"),
2662                super::super::codec::Value::String(id.clone()),
2663            );
2664        }
2665        if !self.extension.is_empty() {
2666            let mut items = Vec::with_capacity(self.extension.len());
2667            for item in &self.extension {
2668                items.push(super::super::codec::Value::Object(
2669                    super::super::codec::Json::to_json(item)?,
2670                ));
2671            }
2672            object.insert(
2673                std::string::String::from("extension"),
2674                super::super::codec::Value::Array(items),
2675            );
2676        }
2677        Ok(Some(super::super::codec::Value::Object(object)))
2678    }
2679
2680    fn has_value(&self) -> bool {
2681        self.value.is_some()
2682    }
2683
2684    fn has_element(&self) -> bool {
2685        self.id.is_some() || !self.extension.is_empty()
2686    }
2687
2688    fn serialize_value<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2689        match self.value.as_ref() {
2690            Some(v) => serde::Serializer::serialize_u32(serializer, *v),
2691            None => serde::Serializer::serialize_none(serializer),
2692        }
2693    }
2694
2695    fn serialize_element<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2696        if self.id.is_none() && self.extension.is_empty() {
2697            return serde::Serializer::serialize_none(serializer);
2698        }
2699        let mut map = serde::Serializer::serialize_map(serializer, None)?;
2700        if !self.extension.is_empty() {
2701            serde::ser::SerializeMap::serialize_entry(&mut map, "extension", &self.extension)?;
2702        }
2703        if let Some(id) = &self.id {
2704            serde::ser::SerializeMap::serialize_entry(&mut map, "id", id)?;
2705        }
2706        serde::ser::SerializeMap::end(map)
2707    }
2708
2709    fn from_json_parts(
2710        value: Option<&super::super::codec::Value>,
2711        element: Option<&super::super::codec::Value>,
2712        path: &mut super::super::codec::Path,
2713    ) -> Result<Self, super::super::codec::DecodeError> {
2714        if value.is_none() && element.is_none() && !path.is_lenient() {
2715            return Err(path.error(super::super::codec::DecodeErrorKind::MissingProperty));
2716        }
2717        let value = match value {
2718            Some(value) => {
2719                let value = super::super::codec::expect_single(value, path)?;
2720                Some(super::super::codec::expect_u32(value, 0, path)?)
2721            }
2722            None => None,
2723        };
2724        let mut id = None;
2725        let mut extension = Vec::new();
2726        if let Some(element) = element {
2727            let object = super::super::codec::expect_object(element, path)?;
2728            for (key, item) in object {
2729                match key.as_str() {
2730                    "id" => {
2731                        id =
2732                            Some(path.with("id", |path| {
2733                                super::super::codec::expect_string(item, path)
2734                            })?);
2735                    }
2736                    "extension" => {
2737                        for (index, entry) in super::super::codec::expect_array(item, path)?
2738                            .iter()
2739                            .enumerate()
2740                        {
2741                            extension.push(path.with_index("extension", index, |path| {
2742                                super::super::codec::Json::from_json(
2743                                    super::super::codec::expect_object(entry, path)?,
2744                                    path,
2745                                )
2746                            })?);
2747                        }
2748                    }
2749                    _ => {
2750                        return path.with(key, |path| {
2751                            Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
2752                        });
2753                    }
2754                }
2755            }
2756        }
2757        Ok(Self {
2758            id,
2759            extension,
2760            value,
2761        })
2762    }
2763}
2764
2765/// Primitive Type uri
2766///
2767/// String of characters used to identify a name or a resource
2768#[derive(Debug, Clone, Default, PartialEq, Eq)]
2769pub struct Uri {
2770    /// xml:id (or equivalent in JSON)
2771    ///
2772    /// unique id for the element within a resource (for internal references)
2773    pub id: Option<std::string::String>,
2774    /// Additional Content defined by implementations
2775    ///
2776    /// May be used to represent additional information that is not part of the
2777    /// basic definition of the resource. In order to make the use of extensions
2778    /// safe and manageable, there is a strict set of governance applied to the
2779    /// definition and use of extensions. Though any implementer is allowed to
2780    /// define an extension, there is a set of requirements that SHALL be met as
2781    /// part of the definition of the extension.
2782    pub extension: Vec<super::extension::Extension>,
2783    /// Primitive value for uri
2784    ///
2785    /// The actual value
2786    pub value: Option<std::string::String>,
2787}
2788impl From<std::string::String> for Uri {
2789    fn from(value: std::string::String) -> Self {
2790        Self {
2791            value: Some(value),
2792            ..Self::default()
2793        }
2794    }
2795}
2796impl From<&str> for Uri {
2797    fn from(value: &str) -> Self {
2798        Self::from(std::string::String::from(value))
2799    }
2800}
2801
2802impl super::super::codec::Primitive for Uri {
2803    fn value_json(
2804        &self,
2805    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
2806        Ok(self
2807            .value
2808            .as_ref()
2809            .map(|v| super::super::codec::Value::String(v.clone())))
2810    }
2811
2812    fn element_json(
2813        &self,
2814    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
2815        if self.id.is_none() && self.extension.is_empty() {
2816            return Ok(None);
2817        }
2818        let mut object = super::super::codec::Object::new();
2819        if let Some(id) = &self.id {
2820            object.insert(
2821                std::string::String::from("id"),
2822                super::super::codec::Value::String(id.clone()),
2823            );
2824        }
2825        if !self.extension.is_empty() {
2826            let mut items = Vec::with_capacity(self.extension.len());
2827            for item in &self.extension {
2828                items.push(super::super::codec::Value::Object(
2829                    super::super::codec::Json::to_json(item)?,
2830                ));
2831            }
2832            object.insert(
2833                std::string::String::from("extension"),
2834                super::super::codec::Value::Array(items),
2835            );
2836        }
2837        Ok(Some(super::super::codec::Value::Object(object)))
2838    }
2839
2840    fn has_value(&self) -> bool {
2841        self.value.is_some()
2842    }
2843
2844    fn has_element(&self) -> bool {
2845        self.id.is_some() || !self.extension.is_empty()
2846    }
2847
2848    fn serialize_value<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2849        match self.value.as_ref() {
2850            Some(v) => serde::Serializer::serialize_str(serializer, v),
2851            None => serde::Serializer::serialize_none(serializer),
2852        }
2853    }
2854
2855    fn serialize_element<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2856        if self.id.is_none() && self.extension.is_empty() {
2857            return serde::Serializer::serialize_none(serializer);
2858        }
2859        let mut map = serde::Serializer::serialize_map(serializer, None)?;
2860        if !self.extension.is_empty() {
2861            serde::ser::SerializeMap::serialize_entry(&mut map, "extension", &self.extension)?;
2862        }
2863        if let Some(id) = &self.id {
2864            serde::ser::SerializeMap::serialize_entry(&mut map, "id", id)?;
2865        }
2866        serde::ser::SerializeMap::end(map)
2867    }
2868
2869    fn from_json_parts(
2870        value: Option<&super::super::codec::Value>,
2871        element: Option<&super::super::codec::Value>,
2872        path: &mut super::super::codec::Path,
2873    ) -> Result<Self, super::super::codec::DecodeError> {
2874        if value.is_none() && element.is_none() && !path.is_lenient() {
2875            return Err(path.error(super::super::codec::DecodeErrorKind::MissingProperty));
2876        }
2877        let value = match value {
2878            Some(value) => {
2879                let value = super::super::codec::expect_single(value, path)?;
2880                Some(super::super::codec::expect_string(value, path)?)
2881            }
2882            None => None,
2883        };
2884        let mut id = None;
2885        let mut extension = Vec::new();
2886        if let Some(element) = element {
2887            let object = super::super::codec::expect_object(element, path)?;
2888            for (key, item) in object {
2889                match key.as_str() {
2890                    "id" => {
2891                        id =
2892                            Some(path.with("id", |path| {
2893                                super::super::codec::expect_string(item, path)
2894                            })?);
2895                    }
2896                    "extension" => {
2897                        for (index, entry) in super::super::codec::expect_array(item, path)?
2898                            .iter()
2899                            .enumerate()
2900                        {
2901                            extension.push(path.with_index("extension", index, |path| {
2902                                super::super::codec::Json::from_json(
2903                                    super::super::codec::expect_object(entry, path)?,
2904                                    path,
2905                                )
2906                            })?);
2907                        }
2908                    }
2909                    _ => {
2910                        return path.with(key, |path| {
2911                            Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
2912                        });
2913                    }
2914                }
2915            }
2916        }
2917        Ok(Self {
2918            id,
2919            extension,
2920            value,
2921        })
2922    }
2923}
2924
2925/// Primitive Type xhtml
2926///
2927/// XHTML
2928#[derive(Debug, Clone, Default, PartialEq, Eq)]
2929pub struct Xhtml {
2930    /// xml:id (or equivalent in JSON)
2931    ///
2932    /// unique id for the element within a resource (for internal references)
2933    pub id: Option<std::string::String>,
2934    /// Actual xhtml
2935    pub value: std::string::String,
2936}
2937impl From<std::string::String> for Xhtml {
2938    fn from(value: std::string::String) -> Self {
2939        Self {
2940            value,
2941            ..Self::default()
2942        }
2943    }
2944}
2945impl From<&str> for Xhtml {
2946    fn from(value: &str) -> Self {
2947        Self::from(std::string::String::from(value))
2948    }
2949}
2950
2951impl super::super::codec::Primitive for Xhtml {
2952    fn value_json(
2953        &self,
2954    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
2955        Ok(Some(&self.value).map(|v| super::super::codec::Value::String(v.clone())))
2956    }
2957
2958    fn element_json(
2959        &self,
2960    ) -> Result<Option<super::super::codec::Value>, super::super::codec::EncodeError> {
2961        if self.id.is_none() {
2962            return Ok(None);
2963        }
2964        let mut object = super::super::codec::Object::new();
2965        if let Some(id) = &self.id {
2966            object.insert(
2967                std::string::String::from("id"),
2968                super::super::codec::Value::String(id.clone()),
2969            );
2970        }
2971        Ok(Some(super::super::codec::Value::Object(object)))
2972    }
2973
2974    fn has_value(&self) -> bool {
2975        true
2976    }
2977
2978    fn has_element(&self) -> bool {
2979        self.id.is_some()
2980    }
2981
2982    fn serialize_value<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2983        serde::Serializer::serialize_str(serializer, &self.value)
2984    }
2985
2986    fn serialize_element<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2987        if self.id.is_none() {
2988            return serde::Serializer::serialize_none(serializer);
2989        }
2990        let mut map = serde::Serializer::serialize_map(serializer, None)?;
2991        if let Some(id) = &self.id {
2992            serde::ser::SerializeMap::serialize_entry(&mut map, "id", id)?;
2993        }
2994        serde::ser::SerializeMap::end(map)
2995    }
2996
2997    fn from_json_parts(
2998        value: Option<&super::super::codec::Value>,
2999        element: Option<&super::super::codec::Value>,
3000        path: &mut super::super::codec::Path,
3001    ) -> Result<Self, super::super::codec::DecodeError> {
3002        if value.is_none() && element.is_none() && !path.is_lenient() {
3003            return Err(path.error(super::super::codec::DecodeErrorKind::MissingProperty));
3004        }
3005        let value = match value {
3006            Some(value) => {
3007                let value = super::super::codec::expect_single(value, path)?;
3008                Some(super::super::codec::expect_string(value, path)?)
3009            }
3010            None => None,
3011        };
3012        let value = value
3013            .ok_or_else(|| path.error(super::super::codec::DecodeErrorKind::MissingProperty))?;
3014        let mut id = None;
3015        if let Some(element) = element {
3016            let object = super::super::codec::expect_object(element, path)?;
3017            for (key, item) in object {
3018                match key.as_str() {
3019                    "id" => {
3020                        id =
3021                            Some(path.with("id", |path| {
3022                                super::super::codec::expect_string(item, path)
3023                            })?);
3024                    }
3025                    _ => {
3026                        return path.with(key, |path| {
3027                            Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
3028                        });
3029                    }
3030                }
3031            }
3032        }
3033        Ok(Self { id, value })
3034    }
3035}
3036
3037/// Checks `value` as the JSON value of the FHIR primitive `code`: its JSON type,
3038/// its lexical form and, for an integer type, its range, exactly as the decoder does
3039/// (<https://hl7.org/fhir/STU3/datatypes.html#primitive>).
3040///
3041/// Answers `None` when this version defines no primitive named `code`.
3042///
3043/// # Errors
3044///
3045/// The inner result is the decoder's [`super::super::codec::DecodeError`] at the path `code` for a value
3046/// the primitive refuses.
3047#[must_use]
3048pub fn check_value(
3049    code: &str,
3050    value: &super::super::codec::Value,
3051) -> Option<Result<(), super::super::codec::DecodeError>> {
3052    let mut path = super::super::codec::Path::root(code);
3053    let checked = match code {
3054        #[cfg(feature = "terminology")]
3055        "base64Binary" => <Base64Binary as super::super::codec::Primitive>::from_json_parts(
3056            Some(value),
3057            None,
3058            &mut path,
3059        )
3060        .map(|_| ()),
3061        #[cfg(feature = "terminology")]
3062        "boolean" => <Boolean as super::super::codec::Primitive>::from_json_parts(
3063            Some(value),
3064            None,
3065            &mut path,
3066        )
3067        .map(|_| ()),
3068        #[cfg(feature = "terminology")]
3069        "code" => {
3070            <Code as super::super::codec::Primitive>::from_json_parts(Some(value), None, &mut path)
3071                .map(|_| ())
3072        }
3073        #[cfg(feature = "terminology")]
3074        "date" => {
3075            <Date as super::super::codec::Primitive>::from_json_parts(Some(value), None, &mut path)
3076                .map(|_| ())
3077        }
3078        #[cfg(feature = "terminology")]
3079        "dateTime" => <DateTime as super::super::codec::Primitive>::from_json_parts(
3080            Some(value),
3081            None,
3082            &mut path,
3083        )
3084        .map(|_| ()),
3085        #[cfg(feature = "terminology")]
3086        "decimal" => <Decimal as super::super::codec::Primitive>::from_json_parts(
3087            Some(value),
3088            None,
3089            &mut path,
3090        )
3091        .map(|_| ()),
3092        #[cfg(feature = "terminology")]
3093        "id" => {
3094            <Id as super::super::codec::Primitive>::from_json_parts(Some(value), None, &mut path)
3095                .map(|_| ())
3096        }
3097        #[cfg(feature = "terminology")]
3098        "instant" => <Instant as super::super::codec::Primitive>::from_json_parts(
3099            Some(value),
3100            None,
3101            &mut path,
3102        )
3103        .map(|_| ()),
3104        #[cfg(feature = "terminology")]
3105        "integer" => <Integer as super::super::codec::Primitive>::from_json_parts(
3106            Some(value),
3107            None,
3108            &mut path,
3109        )
3110        .map(|_| ()),
3111        #[cfg(feature = "terminology")]
3112        "markdown" => <Markdown as super::super::codec::Primitive>::from_json_parts(
3113            Some(value),
3114            None,
3115            &mut path,
3116        )
3117        .map(|_| ()),
3118        #[cfg(feature = "terminology")]
3119        "oid" => {
3120            <Oid as super::super::codec::Primitive>::from_json_parts(Some(value), None, &mut path)
3121                .map(|_| ())
3122        }
3123        #[cfg(feature = "terminology")]
3124        "positiveInt" => <PositiveInt as super::super::codec::Primitive>::from_json_parts(
3125            Some(value),
3126            None,
3127            &mut path,
3128        )
3129        .map(|_| ()),
3130        #[cfg(feature = "terminology")]
3131        "string" => <String as super::super::codec::Primitive>::from_json_parts(
3132            Some(value),
3133            None,
3134            &mut path,
3135        )
3136        .map(|_| ()),
3137        #[cfg(feature = "terminology")]
3138        "time" => {
3139            <Time as super::super::codec::Primitive>::from_json_parts(Some(value), None, &mut path)
3140                .map(|_| ())
3141        }
3142        #[cfg(feature = "terminology")]
3143        "unsignedInt" => <UnsignedInt as super::super::codec::Primitive>::from_json_parts(
3144            Some(value),
3145            None,
3146            &mut path,
3147        )
3148        .map(|_| ()),
3149        #[cfg(feature = "terminology")]
3150        "uri" => {
3151            <Uri as super::super::codec::Primitive>::from_json_parts(Some(value), None, &mut path)
3152                .map(|_| ())
3153        }
3154        #[cfg(feature = "terminology")]
3155        "xhtml" => {
3156            <Xhtml as super::super::codec::Primitive>::from_json_parts(Some(value), None, &mut path)
3157                .map(|_| ())
3158        }
3159        _ => return None,
3160    };
3161    Some(checked)
3162}