use crate::encoding::HL7Encoding;
use crate::error::Hl7Error;
use crate::sub_component::SubComponent;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Component {
raw: String,
pub sub_components: Vec<SubComponent>,
pub is_subcomponentized: bool,
}
impl Component {
pub fn parse(raw: &str, enc: &HL7Encoding) -> Self {
let sub_components: Vec<SubComponent> = raw
.split(enc.subcomponent_delimiter)
.map(SubComponent::new)
.collect();
let is_subcomponentized = sub_components.len() > 1;
Self { raw: raw.to_string(), sub_components, is_subcomponentized }
}
pub(crate) fn single(raw: &str) -> Self {
Self {
raw: raw.to_string(),
sub_components: vec![SubComponent::new(raw)],
is_subcomponentized: false,
}
}
pub fn raw(&self, enc: &HL7Encoding) -> Option<&str> {
if self.raw == enc.present_but_null {
None
} else {
Some(&self.raw)
}
}
pub fn value(&self, enc: &HL7Encoding) -> Option<String> {
if self.raw == enc.present_but_null {
None
} else {
Some(enc.decode(&self.raw))
}
}
pub fn set_value(&mut self, value: &str, enc: &HL7Encoding) {
*self = Component::parse(value, enc);
}
pub fn sub_component(&self, position: usize) -> Result<&SubComponent, Hl7Error> {
position
.checked_sub(1)
.and_then(|i| self.sub_components.get(i))
.ok_or_else(|| Hl7Error::new("SubComponent not available"))
}
}