Skip to main content

fhir_types/r5/
usage_context.rs

1// @generated by fhir-codegen from hl7.fhir.r5.core 5.0.0. 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//! Describes the context of use for a conformance or knowledge resource
6
7/// Describes the context of use for a conformance or knowledge resource
8///
9/// Specifies clinical/business/etc. metadata that can be used to retrieve,
10/// index and/or categorize an artifact. This metadata can either be specific to
11/// the applicable population (e.g., age category, DRG) or the specific context
12/// of care (e.g., venue, care setting, provider of care).
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct UsageContext {
15    /// Unique id for inter-element referencing
16    ///
17    /// Unique id for the element within a resource (for internal references). This
18    /// may be any string value that does not contain spaces.
19    pub id: Option<std::string::String>,
20    /// Additional content defined by implementations
21    ///
22    /// May be used to represent additional information that is not part of the
23    /// basic definition of the element. To make the use of extensions safe and
24    /// managable, there is a strict set of governance applied to the definition and
25    /// use of extensions. Though any implementer can define an extension, there is
26    /// a set of requirements that SHALL be met as part of the definition of the
27    /// extension.
28    pub extension: Vec<super::extension::Extension>,
29    /// Type of context being specified
30    ///
31    /// A code that identifies the type of context being specified by this usage
32    /// context.
33    pub code: super::coding::Coding,
34    /// Value that defines the context
35    ///
36    /// A value that defines the context specified in this context of use. The
37    /// interpretation of the value is defined by the code.
38    pub value: UsageContextValue,
39}
40
41impl super::super::codec::Json for UsageContext {
42    fn to_json(&self) -> Result<super::super::codec::Object, super::super::codec::EncodeError> {
43        let mut object = super::super::codec::Object::new();
44        if let Some(v) = &self.id {
45            object.insert(
46                std::string::String::from("id"),
47                super::super::codec::Value::String(v.clone()),
48            );
49        }
50        if !self.extension.is_empty() {
51            let mut items = Vec::with_capacity(self.extension.len());
52            for item in &self.extension {
53                items.push(super::super::codec::Value::Object(
54                    super::super::codec::Json::to_json(item)?,
55                ));
56            }
57            object.insert(
58                std::string::String::from("extension"),
59                super::super::codec::Value::Array(items),
60            );
61        }
62        object.insert(
63            std::string::String::from("code"),
64            super::super::codec::Value::Object(super::super::codec::Json::to_json(&self.code)?),
65        );
66        let (suffix, value, element) = self.value.to_json_parts()?;
67        if let Some(value) = value {
68            object.insert(format!("value{suffix}"), value);
69        }
70        if let Some(element) = element {
71            object.insert(format!("_value{suffix}"), element);
72        }
73        Ok(object)
74    }
75
76    fn from_json(
77        object: &super::super::codec::Object,
78        path: &mut super::super::codec::Path,
79    ) -> Result<Self, super::super::codec::DecodeError> {
80        let mut raw_id: Option<&super::super::codec::Value> = None;
81        let mut raw_extension: Option<&super::super::codec::Value> = None;
82        let mut raw_code: Option<&super::super::codec::Value> = None;
83        let mut raw_value = super::super::codec::ChoiceSlot::default();
84        for (key, value) in object {
85            match key.as_str() {
86                "id" => {
87                    raw_id = Some(value);
88                }
89                "extension" => {
90                    raw_extension = Some(value);
91                }
92                "code" => {
93                    raw_code = Some(value);
94                }
95                "valueCodeableConcept" => {
96                    raw_value.value("CodeableConcept", value, path)?;
97                }
98                "_valueCodeableConcept" => {
99                    raw_value.element("CodeableConcept", value, path)?;
100                }
101                "valueQuantity" => {
102                    raw_value.value("Quantity", value, path)?;
103                }
104                "_valueQuantity" => {
105                    raw_value.element("Quantity", value, path)?;
106                }
107                "valueRange" => {
108                    raw_value.value("Range", value, path)?;
109                }
110                "_valueRange" => {
111                    raw_value.element("Range", value, path)?;
112                }
113                "valueReference" => {
114                    raw_value.value("Reference", value, path)?;
115                }
116                "_valueReference" => {
117                    raw_value.element("Reference", value, path)?;
118                }
119                other => {
120                    return path.with(other, |path| {
121                        Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
122                    });
123                }
124            }
125        }
126        let field_id = raw_id
127            .map(|value| {
128                path.with("id", |path| {
129                    let value = super::super::codec::expect_single(value, path)?;
130                    super::primitives::checked_string(
131                        super::super::codec::expect_string(value, path)?,
132                        path,
133                    )
134                })
135            })
136            .transpose()?;
137        let mut field_extension = Vec::new();
138        if let Some(raw) = raw_extension {
139            for (index, value) in path
140                .with("extension", |path| {
141                    super::super::codec::expect_array(raw, path)
142                })?
143                .iter()
144                .enumerate()
145            {
146                field_extension.push(path.with_index("extension", index, |path| {
147                    super::super::codec::Json::from_json(
148                        super::super::codec::expect_object(value, path)?,
149                        path,
150                    )
151                })?);
152            }
153        }
154        let field_code = path.with("code", |path| {
155            let value = raw_code
156                .ok_or_else(|| path.error(super::super::codec::DecodeErrorKind::MissingProperty))?;
157            super::super::codec::Json::from_json(
158                super::super::codec::expect_object(
159                    super::super::codec::expect_single(value, path)?,
160                    path,
161                )?,
162                path,
163            )
164        })?;
165        let field_value = path.with("value", |path| {
166            let suffix = raw_value
167                .suffix
168                .ok_or_else(|| path.error(super::super::codec::DecodeErrorKind::MissingProperty))?;
169            UsageContextValue::from_json_parts(suffix, raw_value.value, raw_value.element, path)
170        })?;
171        Ok(Self {
172            id: field_id,
173            extension: field_extension,
174            code: field_code,
175            value: field_value,
176        })
177    }
178}
179
180impl serde::Serialize for UsageContext {
181    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
182        let mut map = serde::Serializer::serialize_map(serializer, None)?;
183        serde::ser::SerializeMap::serialize_entry(&mut map, "code", &self.code)?;
184        if !self.extension.is_empty() {
185            serde::ser::SerializeMap::serialize_entry(&mut map, "extension", &self.extension)?;
186        }
187        if let Some(v) = &self.id {
188            serde::ser::SerializeMap::serialize_entry(&mut map, "id", v)?;
189        }
190        match &self.value {
191            UsageContextValue::CodeableConcept(inner) => {
192                serde::ser::SerializeMap::serialize_entry(
193                    &mut map,
194                    "valueCodeableConcept",
195                    inner.as_ref(),
196                )?;
197            }
198            UsageContextValue::Quantity(inner) => {
199                serde::ser::SerializeMap::serialize_entry(
200                    &mut map,
201                    "valueQuantity",
202                    inner.as_ref(),
203                )?;
204            }
205            UsageContextValue::Range(inner) => {
206                serde::ser::SerializeMap::serialize_entry(&mut map, "valueRange", inner.as_ref())?;
207            }
208            UsageContextValue::Reference(inner) => {
209                serde::ser::SerializeMap::serialize_entry(
210                    &mut map,
211                    "valueReference",
212                    inner.as_ref(),
213                )?;
214            }
215        }
216        serde::ser::SerializeMap::end(map)
217    }
218}
219
220impl<'de> serde::Deserialize<'de> for UsageContext {
221    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
222        let value = <super::super::codec::Value as serde::Deserialize>::deserialize(deserializer)?;
223        let mut path = super::super::codec::Path::root("UsageContext");
224        let object =
225            super::super::codec::expect_object(&value, &path).map_err(serde::de::Error::custom)?;
226        super::super::codec::Json::from_json(object, &mut path).map_err(serde::de::Error::custom)
227    }
228}
229
230/// The \`value\[x\]\` choice of \`UsageContext\`.
231///
232/// A value that defines the context specified in this context of use. The
233/// interpretation of the value is defined by the code.
234#[derive(Debug, Clone, PartialEq, Eq)]
235pub enum UsageContextValue {
236    /// The `CodeableConcept` form.
237    CodeableConcept(Box<super::codeable_concept::CodeableConcept>),
238    /// The `Quantity` form.
239    Quantity(Box<super::quantity::Quantity>),
240    /// The `Range` form.
241    Range(Box<super::range::Range>),
242    /// The `Reference` form.
243    Reference(Box<super::reference::Reference>),
244}
245
246impl UsageContextValue {
247    /// The key suffix, the value part, and the `_name` part of this form.
248    ///
249    /// # Errors
250    ///
251    /// Returns [`super::super::codec::EncodeError`] when a held value has no JSON form.
252    pub fn to_json_parts(
253        &self,
254    ) -> Result<
255        (
256            &'static str,
257            Option<super::super::codec::Value>,
258            Option<super::super::codec::Value>,
259        ),
260        super::super::codec::EncodeError,
261    > {
262        match self {
263            Self::CodeableConcept(inner) => Ok((
264                "CodeableConcept",
265                Some(super::super::codec::Value::Object(
266                    super::super::codec::Json::to_json(inner.as_ref())?,
267                )),
268                None,
269            )),
270            Self::Quantity(inner) => Ok((
271                "Quantity",
272                Some(super::super::codec::Value::Object(
273                    super::super::codec::Json::to_json(inner.as_ref())?,
274                )),
275                None,
276            )),
277            Self::Range(inner) => Ok((
278                "Range",
279                Some(super::super::codec::Value::Object(
280                    super::super::codec::Json::to_json(inner.as_ref())?,
281                )),
282                None,
283            )),
284            Self::Reference(inner) => Ok((
285                "Reference",
286                Some(super::super::codec::Value::Object(
287                    super::super::codec::Json::to_json(inner.as_ref())?,
288                )),
289                None,
290            )),
291        }
292    }
293
294    /// Decodes the form named by `suffix` from its value and `_name` parts.
295    ///
296    /// # Errors
297    ///
298    /// Returns [`super::super::codec::DecodeError`] for an unknown suffix or a malformed part.
299    pub fn from_json_parts(
300        suffix: &str,
301        value: Option<&super::super::codec::Value>,
302        element: Option<&super::super::codec::Value>,
303        path: &mut super::super::codec::Path,
304    ) -> Result<Self, super::super::codec::DecodeError> {
305        match suffix {
306            "CodeableConcept" => {
307                if element.is_some() {
308                    return Err(path.error(super::super::codec::DecodeErrorKind::WrongType {
309                        expected: "no underscore form for a complex type",
310                    }));
311                }
312                let value = value.ok_or_else(|| {
313                    path.error(super::super::codec::DecodeErrorKind::MissingProperty)
314                })?;
315                let inner = super::super::codec::Json::from_json(
316                    super::super::codec::expect_object(
317                        super::super::codec::expect_single(value, path)?,
318                        path,
319                    )?,
320                    path,
321                )?;
322                Ok(Self::CodeableConcept(Box::new(inner)))
323            }
324            "Quantity" => {
325                if element.is_some() {
326                    return Err(path.error(super::super::codec::DecodeErrorKind::WrongType {
327                        expected: "no underscore form for a complex type",
328                    }));
329                }
330                let value = value.ok_or_else(|| {
331                    path.error(super::super::codec::DecodeErrorKind::MissingProperty)
332                })?;
333                let inner = super::super::codec::Json::from_json(
334                    super::super::codec::expect_object(
335                        super::super::codec::expect_single(value, path)?,
336                        path,
337                    )?,
338                    path,
339                )?;
340                Ok(Self::Quantity(Box::new(inner)))
341            }
342            "Range" => {
343                if element.is_some() {
344                    return Err(path.error(super::super::codec::DecodeErrorKind::WrongType {
345                        expected: "no underscore form for a complex type",
346                    }));
347                }
348                let value = value.ok_or_else(|| {
349                    path.error(super::super::codec::DecodeErrorKind::MissingProperty)
350                })?;
351                let inner = super::super::codec::Json::from_json(
352                    super::super::codec::expect_object(
353                        super::super::codec::expect_single(value, path)?,
354                        path,
355                    )?,
356                    path,
357                )?;
358                Ok(Self::Range(Box::new(inner)))
359            }
360            "Reference" => {
361                if element.is_some() {
362                    return Err(path.error(super::super::codec::DecodeErrorKind::WrongType {
363                        expected: "no underscore form for a complex type",
364                    }));
365                }
366                let value = value.ok_or_else(|| {
367                    path.error(super::super::codec::DecodeErrorKind::MissingProperty)
368                })?;
369                let inner = super::super::codec::Json::from_json(
370                    super::super::codec::expect_object(
371                        super::super::codec::expect_single(value, path)?,
372                        path,
373                    )?,
374                    path,
375                )?;
376                Ok(Self::Reference(Box::new(inner)))
377            }
378            _ => Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty)),
379        }
380    }
381}