Skip to main content

fhir_types/r6/
usage_context.rs

1// @generated by fhir-codegen from hl7.fhir.r6.core 6.0.0-ballot5. 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(s) that define the context
35    ///
36    /// A value or set of possible values that defines the context specified in this
37    /// context of use. The interpretation of the value is defined by the code. If a
38    /// 'range' is specified, then the context means that the artifact applies for
39    /// any value of the context that falls within range. If a 'valueset' is
40    /// specified, then the context means that the artifact applies if a code
41    /// matches the value set.
42    pub value: UsageContextValue,
43}
44
45impl super::super::codec::Json for UsageContext {
46    fn to_json(&self) -> Result<super::super::codec::Object, super::super::codec::EncodeError> {
47        let mut object = super::super::codec::Object::new();
48        if let Some(v) = &self.id {
49            object.insert(
50                std::string::String::from("id"),
51                super::super::codec::Value::String(v.clone()),
52            );
53        }
54        if !self.extension.is_empty() {
55            let mut items = Vec::with_capacity(self.extension.len());
56            for item in &self.extension {
57                items.push(super::super::codec::Value::Object(
58                    super::super::codec::Json::to_json(item)?,
59                ));
60            }
61            object.insert(
62                std::string::String::from("extension"),
63                super::super::codec::Value::Array(items),
64            );
65        }
66        object.insert(
67            std::string::String::from("code"),
68            super::super::codec::Value::Object(super::super::codec::Json::to_json(&self.code)?),
69        );
70        let (suffix, value, element) = self.value.to_json_parts()?;
71        if let Some(value) = value {
72            object.insert(format!("value{suffix}"), value);
73        }
74        if let Some(element) = element {
75            object.insert(format!("_value{suffix}"), element);
76        }
77        Ok(object)
78    }
79
80    fn from_json(
81        object: &super::super::codec::Object,
82        path: &mut super::super::codec::Path,
83    ) -> Result<Self, super::super::codec::DecodeError> {
84        let mut raw_id: Option<&super::super::codec::Value> = None;
85        let mut raw_extension: Option<&super::super::codec::Value> = None;
86        let mut raw_code: Option<&super::super::codec::Value> = None;
87        let mut raw_value = super::super::codec::ChoiceSlot::default();
88        for (key, value) in object {
89            match key.as_str() {
90                "id" => {
91                    raw_id = Some(value);
92                }
93                "extension" => {
94                    raw_extension = Some(value);
95                }
96                "code" => {
97                    raw_code = Some(value);
98                }
99                "valueCodeableConcept" => {
100                    raw_value.value("CodeableConcept", value, path)?;
101                }
102                "_valueCodeableConcept" => {
103                    raw_value.element("CodeableConcept", value, path)?;
104                }
105                "valueQuantity" => {
106                    raw_value.value("Quantity", value, path)?;
107                }
108                "_valueQuantity" => {
109                    raw_value.element("Quantity", value, path)?;
110                }
111                "valueRange" => {
112                    raw_value.value("Range", value, path)?;
113                }
114                "_valueRange" => {
115                    raw_value.element("Range", value, path)?;
116                }
117                "valueReference" => {
118                    raw_value.value("Reference", value, path)?;
119                }
120                "_valueReference" => {
121                    raw_value.element("Reference", value, path)?;
122                }
123                "valueCanonical" => {
124                    raw_value.value("Canonical", value, path)?;
125                }
126                "_valueCanonical" => {
127                    raw_value.element("Canonical", value, path)?;
128                }
129                other => {
130                    return path.with(other, |path| {
131                        Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
132                    });
133                }
134            }
135        }
136        let field_id = raw_id
137            .map(|value| {
138                path.with("id", |path| {
139                    let value = super::super::codec::expect_single(value, path)?;
140                    super::primitives::checked_string(
141                        super::super::codec::expect_string(value, path)?,
142                        path,
143                    )
144                })
145            })
146            .transpose()?;
147        let mut field_extension = Vec::new();
148        if let Some(raw) = raw_extension {
149            for (index, value) in path
150                .with("extension", |path| {
151                    super::super::codec::expect_array(raw, path)
152                })?
153                .iter()
154                .enumerate()
155            {
156                field_extension.push(path.with_index("extension", index, |path| {
157                    super::super::codec::Json::from_json(
158                        super::super::codec::expect_object(value, path)?,
159                        path,
160                    )
161                })?);
162            }
163        }
164        let field_code = path.with("code", |path| {
165            let value = raw_code
166                .ok_or_else(|| path.error(super::super::codec::DecodeErrorKind::MissingProperty))?;
167            super::super::codec::Json::from_json(
168                super::super::codec::expect_object(
169                    super::super::codec::expect_single(value, path)?,
170                    path,
171                )?,
172                path,
173            )
174        })?;
175        let field_value = path.with("value", |path| {
176            let suffix = raw_value
177                .suffix
178                .ok_or_else(|| path.error(super::super::codec::DecodeErrorKind::MissingProperty))?;
179            UsageContextValue::from_json_parts(suffix, raw_value.value, raw_value.element, path)
180        })?;
181        Ok(Self {
182            id: field_id,
183            extension: field_extension,
184            code: field_code,
185            value: field_value,
186        })
187    }
188}
189
190impl serde::Serialize for UsageContext {
191    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
192        let mut map = serde::Serializer::serialize_map(serializer, None)?;
193        if let UsageContextValue::Canonical(inner) = &self.value {
194            super::super::codec::element_entry(&mut map, "_valueCanonical", inner)?;
195        }
196        serde::ser::SerializeMap::serialize_entry(&mut map, "code", &self.code)?;
197        if !self.extension.is_empty() {
198            serde::ser::SerializeMap::serialize_entry(&mut map, "extension", &self.extension)?;
199        }
200        if let Some(v) = &self.id {
201            serde::ser::SerializeMap::serialize_entry(&mut map, "id", v)?;
202        }
203        match &self.value {
204            UsageContextValue::Canonical(inner) => {
205                super::super::codec::value_entry(&mut map, "valueCanonical", inner)?;
206            }
207            UsageContextValue::CodeableConcept(inner) => {
208                serde::ser::SerializeMap::serialize_entry(
209                    &mut map,
210                    "valueCodeableConcept",
211                    inner.as_ref(),
212                )?;
213            }
214            UsageContextValue::Quantity(inner) => {
215                serde::ser::SerializeMap::serialize_entry(
216                    &mut map,
217                    "valueQuantity",
218                    inner.as_ref(),
219                )?;
220            }
221            UsageContextValue::Range(inner) => {
222                serde::ser::SerializeMap::serialize_entry(&mut map, "valueRange", inner.as_ref())?;
223            }
224            UsageContextValue::Reference(inner) => {
225                serde::ser::SerializeMap::serialize_entry(
226                    &mut map,
227                    "valueReference",
228                    inner.as_ref(),
229                )?;
230            }
231        }
232        serde::ser::SerializeMap::end(map)
233    }
234}
235
236impl<'de> serde::Deserialize<'de> for UsageContext {
237    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
238        let value = <super::super::codec::Value as serde::Deserialize>::deserialize(deserializer)?;
239        let mut path = super::super::codec::Path::root("UsageContext");
240        let object =
241            super::super::codec::expect_object(&value, &path).map_err(serde::de::Error::custom)?;
242        super::super::codec::Json::from_json(object, &mut path).map_err(serde::de::Error::custom)
243    }
244}
245
246/// The \`value\[x\]\` choice of \`UsageContext\`.
247///
248/// A value or set of possible values that defines the context specified in this
249/// context of use. The interpretation of the value is defined by the code. If a
250/// 'range' is specified, then the context means that the artifact applies for
251/// any value of the context that falls within range. If a 'valueset' is
252/// specified, then the context means that the artifact applies if a code
253/// matches the value set.
254#[derive(Debug, Clone, PartialEq, Eq)]
255pub enum UsageContextValue {
256    /// The `CodeableConcept` form.
257    CodeableConcept(Box<super::codeable_concept::CodeableConcept>),
258    /// The `Quantity` form.
259    Quantity(Box<super::quantity::Quantity>),
260    /// The `Range` form.
261    Range(Box<super::range::Range>),
262    /// The `Reference` form.
263    Reference(Box<super::reference::Reference>),
264    /// The `canonical` form.
265    Canonical(super::primitives::Canonical),
266}
267
268impl UsageContextValue {
269    /// The key suffix, the value part, and the `_name` part of this form.
270    ///
271    /// # Errors
272    ///
273    /// Returns [`super::super::codec::EncodeError`] when a held value has no JSON form.
274    pub fn to_json_parts(
275        &self,
276    ) -> Result<
277        (
278            &'static str,
279            Option<super::super::codec::Value>,
280            Option<super::super::codec::Value>,
281        ),
282        super::super::codec::EncodeError,
283    > {
284        match self {
285            Self::CodeableConcept(inner) => Ok((
286                "CodeableConcept",
287                Some(super::super::codec::Value::Object(
288                    super::super::codec::Json::to_json(inner.as_ref())?,
289                )),
290                None,
291            )),
292            Self::Quantity(inner) => Ok((
293                "Quantity",
294                Some(super::super::codec::Value::Object(
295                    super::super::codec::Json::to_json(inner.as_ref())?,
296                )),
297                None,
298            )),
299            Self::Range(inner) => Ok((
300                "Range",
301                Some(super::super::codec::Value::Object(
302                    super::super::codec::Json::to_json(inner.as_ref())?,
303                )),
304                None,
305            )),
306            Self::Reference(inner) => Ok((
307                "Reference",
308                Some(super::super::codec::Value::Object(
309                    super::super::codec::Json::to_json(inner.as_ref())?,
310                )),
311                None,
312            )),
313            Self::Canonical(inner) => Ok((
314                "Canonical",
315                super::super::codec::Primitive::value_json(inner)?,
316                super::super::codec::Primitive::element_json(inner)?,
317            )),
318        }
319    }
320
321    /// Decodes the form named by `suffix` from its value and `_name` parts.
322    ///
323    /// # Errors
324    ///
325    /// Returns [`super::super::codec::DecodeError`] for an unknown suffix or a malformed part.
326    pub fn from_json_parts(
327        suffix: &str,
328        value: Option<&super::super::codec::Value>,
329        element: Option<&super::super::codec::Value>,
330        path: &mut super::super::codec::Path,
331    ) -> Result<Self, super::super::codec::DecodeError> {
332        match suffix {
333            "CodeableConcept" => {
334                if element.is_some() {
335                    return Err(path.error(super::super::codec::DecodeErrorKind::WrongType {
336                        expected: "no underscore form for a complex type",
337                    }));
338                }
339                let value = value.ok_or_else(|| {
340                    path.error(super::super::codec::DecodeErrorKind::MissingProperty)
341                })?;
342                let inner = super::super::codec::Json::from_json(
343                    super::super::codec::expect_object(
344                        super::super::codec::expect_single(value, path)?,
345                        path,
346                    )?,
347                    path,
348                )?;
349                Ok(Self::CodeableConcept(Box::new(inner)))
350            }
351            "Quantity" => {
352                if element.is_some() {
353                    return Err(path.error(super::super::codec::DecodeErrorKind::WrongType {
354                        expected: "no underscore form for a complex type",
355                    }));
356                }
357                let value = value.ok_or_else(|| {
358                    path.error(super::super::codec::DecodeErrorKind::MissingProperty)
359                })?;
360                let inner = super::super::codec::Json::from_json(
361                    super::super::codec::expect_object(
362                        super::super::codec::expect_single(value, path)?,
363                        path,
364                    )?,
365                    path,
366                )?;
367                Ok(Self::Quantity(Box::new(inner)))
368            }
369            "Range" => {
370                if element.is_some() {
371                    return Err(path.error(super::super::codec::DecodeErrorKind::WrongType {
372                        expected: "no underscore form for a complex type",
373                    }));
374                }
375                let value = value.ok_or_else(|| {
376                    path.error(super::super::codec::DecodeErrorKind::MissingProperty)
377                })?;
378                let inner = super::super::codec::Json::from_json(
379                    super::super::codec::expect_object(
380                        super::super::codec::expect_single(value, path)?,
381                        path,
382                    )?,
383                    path,
384                )?;
385                Ok(Self::Range(Box::new(inner)))
386            }
387            "Reference" => {
388                if element.is_some() {
389                    return Err(path.error(super::super::codec::DecodeErrorKind::WrongType {
390                        expected: "no underscore form for a complex type",
391                    }));
392                }
393                let value = value.ok_or_else(|| {
394                    path.error(super::super::codec::DecodeErrorKind::MissingProperty)
395                })?;
396                let inner = super::super::codec::Json::from_json(
397                    super::super::codec::expect_object(
398                        super::super::codec::expect_single(value, path)?,
399                        path,
400                    )?,
401                    path,
402                )?;
403                Ok(Self::Reference(Box::new(inner)))
404            }
405            "Canonical" => Ok(Self::Canonical(
406                super::super::codec::Primitive::from_json_parts(value, element, path)?,
407            )),
408            _ => Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty)),
409        }
410    }
411}