fhir-types 0.1.115

Generated per-version FHIR types and terminology operation contracts
Documentation
// @generated by fhir-codegen from hl7.fhir.r5.core 5.0.0. DO NOT EDIT.
// Change the emitter (tools/fhir-codegen) and regenerate.
// SPDX-FileCopyrightText: Cadasto B.V.
// SPDX-License-Identifier: Apache-2.0
//! Text node with attribution

/// Text node with attribution
///
/// A text note which also contains information about who made the statement and
/// when.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Annotation {
    /// Unique id for inter-element referencing
    ///
    /// Unique id for the element within a resource (for internal references). This
    /// may be any string value that does not contain spaces.
    pub id: Option<std::string::String>,
    /// Additional content defined by implementations
    ///
    /// May be used to represent additional information that is not part of the
    /// basic definition of the element. To make the use of extensions safe and
    /// managable, there is a strict set of governance applied to the definition and
    /// use of extensions. Though any implementer can define an extension, there is
    /// a set of requirements that SHALL be met as part of the definition of the
    /// extension.
    pub extension: Vec<super::extension::Extension>,
    /// Individual responsible for the annotation
    ///
    /// The individual responsible for making the annotation.
    pub author: Option<AnnotationAuthor>,
    /// When the annotation was made
    ///
    /// Indicates when this particular annotation was made.
    pub time: Option<super::primitives::DateTime>,
    /// The annotation - text content (as markdown)
    ///
    /// The text of the annotation in markdown format.
    pub text: super::primitives::Markdown,
}

impl super::super::codec::Json for Annotation {
    fn to_json(&self) -> Result<super::super::codec::Object, super::super::codec::EncodeError> {
        let mut object = super::super::codec::Object::new();
        if let Some(v) = &self.id {
            object.insert(
                std::string::String::from("id"),
                super::super::codec::Value::String(v.clone()),
            );
        }
        if !self.extension.is_empty() {
            let mut items = Vec::with_capacity(self.extension.len());
            for item in &self.extension {
                items.push(super::super::codec::Value::Object(
                    super::super::codec::Json::to_json(item)?,
                ));
            }
            object.insert(
                std::string::String::from("extension"),
                super::super::codec::Value::Array(items),
            );
        }
        if let Some(item) = &self.author {
            let (suffix, value, element) = item.to_json_parts()?;
            if let Some(value) = value {
                object.insert(format!("author{suffix}"), value);
            }
            if let Some(element) = element {
                object.insert(format!("_author{suffix}"), element);
            }
        }
        if let Some(item) = &self.time {
            if let Some(v) = super::super::codec::Primitive::value_json(item)? {
                object.insert(std::string::String::from("time"), v);
            }
            if let Some(e) = super::super::codec::Primitive::element_json(item)? {
                object.insert(std::string::String::from("_time"), e);
            }
        }
        if let Some(v) = super::super::codec::Primitive::value_json(&self.text)? {
            object.insert(std::string::String::from("text"), v);
        }
        if let Some(e) = super::super::codec::Primitive::element_json(&self.text)? {
            object.insert(std::string::String::from("_text"), e);
        }
        Ok(object)
    }

    fn from_json(
        object: &super::super::codec::Object,
        path: &mut super::super::codec::Path,
    ) -> Result<Self, super::super::codec::DecodeError> {
        let mut raw_id: Option<&super::super::codec::Value> = None;
        let mut raw_extension: Option<&super::super::codec::Value> = None;
        let mut raw_author = super::super::codec::ChoiceSlot::default();
        let mut raw_time: Option<&super::super::codec::Value> = None;
        let mut raw_time_element: Option<&super::super::codec::Value> = None;
        let mut raw_text: Option<&super::super::codec::Value> = None;
        let mut raw_text_element: Option<&super::super::codec::Value> = None;
        for (key, value) in object {
            match key.as_str() {
                "id" => {
                    raw_id = Some(value);
                }
                "extension" => {
                    raw_extension = Some(value);
                }
                "authorReference" => {
                    raw_author.value("Reference", value, path)?;
                }
                "_authorReference" => {
                    raw_author.element("Reference", value, path)?;
                }
                "authorString" => {
                    raw_author.value("String", value, path)?;
                }
                "_authorString" => {
                    raw_author.element("String", value, path)?;
                }
                "time" => {
                    raw_time = Some(value);
                }
                "_time" => {
                    raw_time_element = Some(value);
                }
                "text" => {
                    raw_text = Some(value);
                }
                "_text" => {
                    raw_text_element = Some(value);
                }
                other => {
                    return path.with(other, |path| {
                        Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
                    });
                }
            }
        }
        let field_id = raw_id
            .map(|value| {
                path.with("id", |path| {
                    let value = super::super::codec::expect_single(value, path)?;
                    super::primitives::checked_id(
                        super::super::codec::expect_string(value, path)?,
                        path,
                    )
                })
            })
            .transpose()?;
        let mut field_extension = Vec::new();
        if let Some(raw) = raw_extension {
            for (index, value) in super::super::codec::expect_array(raw, path)?
                .iter()
                .enumerate()
            {
                field_extension.push(path.with_index("extension", index, |path| {
                    super::super::codec::Json::from_json(
                        super::super::codec::expect_object(value, path)?,
                        path,
                    )
                })?);
            }
        }
        let field_author = match raw_author.suffix {
            None => None,
            Some(suffix) => Some(path.with("author", |path| {
                AnnotationAuthor::from_json_parts(
                    suffix,
                    raw_author.value,
                    raw_author.element,
                    path,
                )
            })?),
        };
        let field_time = match (raw_time, raw_time_element) {
            (None, None) => None,
            (value, element) => Some(path.with("time", |path| {
                super::super::codec::Primitive::from_json_parts(value, element, path)
            })?),
        };
        let field_text = path.with("text", |path| {
            super::super::codec::Primitive::from_json_parts(raw_text, raw_text_element, path)
        })?;
        Ok(Self {
            id: field_id,
            extension: field_extension,
            author: field_author,
            time: field_time,
            text: field_text,
        })
    }
}

impl serde::Serialize for Annotation {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut map = serde::Serializer::serialize_map(serializer, None)?;
        if let Some(AnnotationAuthor::String(inner)) = &self.author {
            super::super::codec::element_entry(&mut map, "_authorString", inner)?;
        }
        super::super::codec::element_entry(&mut map, "_text", &self.text)?;
        if let Some(item) = &self.time {
            super::super::codec::element_entry(&mut map, "_time", item)?;
        }
        match &self.author {
            Some(AnnotationAuthor::Reference(inner)) => {
                serde::ser::SerializeMap::serialize_entry(
                    &mut map,
                    "authorReference",
                    inner.as_ref(),
                )?;
            }
            Some(AnnotationAuthor::String(inner)) => {
                super::super::codec::value_entry(&mut map, "authorString", inner)?;
            }
            None => {}
        }
        if !self.extension.is_empty() {
            serde::ser::SerializeMap::serialize_entry(&mut map, "extension", &self.extension)?;
        }
        if let Some(v) = &self.id {
            serde::ser::SerializeMap::serialize_entry(&mut map, "id", v)?;
        }
        super::super::codec::value_entry(&mut map, "text", &self.text)?;
        if let Some(item) = &self.time {
            super::super::codec::value_entry(&mut map, "time", item)?;
        }
        serde::ser::SerializeMap::end(map)
    }
}

impl<'de> serde::Deserialize<'de> for Annotation {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = <super::super::codec::Value as serde::Deserialize>::deserialize(deserializer)?;
        let mut path = super::super::codec::Path::root("Annotation");
        let object =
            super::super::codec::expect_object(&value, &path).map_err(serde::de::Error::custom)?;
        super::super::codec::Json::from_json(object, &mut path).map_err(serde::de::Error::custom)
    }
}

/// The \`author\[x\]\` choice of \`Annotation\`.
///
/// The individual responsible for making the annotation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AnnotationAuthor {
    /// The `Reference` form.
    Reference(Box<super::reference::Reference>),
    /// The `string` form.
    String(super::primitives::String),
}

impl AnnotationAuthor {
    /// The key suffix, the value part, and the `_name` part of this form.
    ///
    /// # Errors
    ///
    /// Returns [`super::super::codec::EncodeError`] when a held value has no JSON form.
    pub fn to_json_parts(
        &self,
    ) -> Result<
        (
            &'static str,
            Option<super::super::codec::Value>,
            Option<super::super::codec::Value>,
        ),
        super::super::codec::EncodeError,
    > {
        match self {
            Self::Reference(inner) => Ok((
                "Reference",
                Some(super::super::codec::Value::Object(
                    super::super::codec::Json::to_json(inner.as_ref())?,
                )),
                None,
            )),
            Self::String(inner) => Ok((
                "String",
                super::super::codec::Primitive::value_json(inner)?,
                super::super::codec::Primitive::element_json(inner)?,
            )),
        }
    }

    /// Decodes the form named by `suffix` from its value and `_name` parts.
    ///
    /// # Errors
    ///
    /// Returns [`super::super::codec::DecodeError`] for an unknown suffix or a malformed part.
    pub fn from_json_parts(
        suffix: &str,
        value: Option<&super::super::codec::Value>,
        element: Option<&super::super::codec::Value>,
        path: &mut super::super::codec::Path,
    ) -> Result<Self, super::super::codec::DecodeError> {
        match suffix {
            "Reference" => {
                if element.is_some() {
                    return Err(path.error(super::super::codec::DecodeErrorKind::WrongType {
                        expected: "no underscore form for a complex type",
                    }));
                }
                let value = value.ok_or_else(|| {
                    path.error(super::super::codec::DecodeErrorKind::MissingProperty)
                })?;
                let inner = super::super::codec::Json::from_json(
                    super::super::codec::expect_object(
                        super::super::codec::expect_single(value, path)?,
                        path,
                    )?,
                    path,
                )?;
                Ok(Self::Reference(Box::new(inner)))
            }
            "String" => Ok(Self::String(
                super::super::codec::Primitive::from_json_parts(value, element, path)?,
            )),
            _ => Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty)),
        }
    }
}