hl7_parser/
repeat.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
use crate::Component;
use std::{
    num::NonZeroUsize,
    ops::{Index, Range},
};

/// Represents an HL7v2 repeat of a field
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Repeat {
    /// The range (in char indices) in the original message where the repeat is located
    pub range: Range<usize>,
    /// The components found within the component
    pub components: Vec<Component>,
}

impl Repeat {
    /// Access a component via the 1-based HL7 component index
    ///
    /// # Returns
    ///
    /// A reference to the component
    #[inline]
    pub fn component(&self, component: NonZeroUsize) -> Option<&Component> {
        self.components.get(component.get() - 1)
    }

    /// Mutably access a component via the 1-based HL7 component index
    ///
    /// # Returns
    ///
    /// A mutable reference to the component
    #[inline]
    pub fn component_mut(&mut self, component: NonZeroUsize) -> Option<&mut Component> {
        self.components.get_mut(component.get() - 1)
    }

    /// Given the source for the original message, extract the (raw) string for this repeat
    ///
    /// # Arguments
    ///
    /// * `message_source` - A string slice representing the original message source that was parsed
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::num::NonZeroUsize;
    /// # use hl7_parser::ParsedMessage;
    /// let message = include_str!("../test_assets/sample_adt_a04.hl7");
    /// let message = ParsedMessage::parse(&message, true).expect("can parse message");
    ///
    /// let segment = message.segment("AL1").expect("can get AL1 segment");
    /// let field = segment.field(NonZeroUsize::new(5).unwrap()).expect("can get field 5");
    /// let repeat = field.repeat(NonZeroUsize::new(2).unwrap()).expect("can get repeat 2");
    ///
    /// assert_eq!(repeat.source(message.source), "RASH");
    /// ```
    #[inline]
    pub fn source<'s>(&self, message_source: &'s str) -> &'s str {
        &message_source[self.range.clone()]
    }

    /// Locate a component at the cursor position
    ///
    /// # Arguments
    ///
    /// * `cursor` - The cursor location (0-based character index of the original message)
    ///
    /// # Returns
    ///
    /// A tuple containing the HL7 component index (1-based) and a reference to the component.
    /// If the repeat doesn't contain the cursor, returns `None`
    pub fn component_at_cursor(&self, cursor: usize) -> Option<(NonZeroUsize, &Component)> {
        if !self.range.contains(&cursor) {
            return None;
        }
        self.components
            .iter()
            .enumerate()
            .find(|(_, component)| {
                component.range.contains(&cursor) || component.range.start == cursor
            })
            .map(|(i, sc)| (NonZeroUsize::new(i + 1).unwrap(), sc))
    }
}

impl<I: Into<usize>> Index<I> for &Repeat {
    type Output = Component;

    fn index(&self, index: I) -> &Self::Output {
        &self.components[index.into()]
    }
}

/// A trait for accessing components on fields, to extend Option<&Repeat> with short-circuit access
pub trait ComponentAccessor {
    /// Access the component given by 1-based indexing
    fn component(&self, component: NonZeroUsize) -> Option<&Component>;
}

impl ComponentAccessor for Option<&Repeat> {
    #[inline]
    fn component(&self, component: NonZeroUsize) -> Option<&Component> {
        match self {
            None => None,
            Some(repeat) => repeat.component(component),
        }
    }
}

/// A trait for accessing components on fields, to extend Option<&mut Repeat> with short-circuit access
pub trait ComponentAccessorMut {
    /// Access the component given by 1-based indexing
    fn component_mut(&mut self, component: NonZeroUsize) -> Option<&mut Component>;
}

impl ComponentAccessorMut for Option<&mut Repeat> {
    #[inline]
    fn component_mut(&mut self, component: NonZeroUsize) -> Option<&mut Component> {
        match self {
            None => None,
            Some(repeat) => repeat.component_mut(component),
        }
    }
}