hl7_parser/message.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 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
use indexmap::IndexMap;
use crate::{
Component, ComponentAccessor, Field, LocationQuery, ParseError, Repeat, RepeatAccessor,
Segment, Segments, Separators, SubComponent, SubComponentAccessor,
};
use std::{num::NonZeroUsize, ops::Range};
/// A parsed message. The message structure is valid, but the contents may or may not be.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct ParsedMessage<'s> {
/// The original source message, generally used to extract items using ranges
pub source: &'s str,
/// The separators & encoding characters defined at the beginning of the MSH segment
pub separators: Separators,
/// All the segments stored within the message
pub segments: IndexMap<&'s str, Segments>,
}
/// A parsed message that owns its string slice. The message structure is valid, but the contents may or may not be.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ParsedMessageOwned {
/// The original source message, generally used to extract items using ranges
pub source: String,
/// The separators & encoding characters defined at the beginning of the MSH segment
pub separators: Separators,
/// All the segments stored within the message
pub segments: IndexMap<String, Segments>,
}
impl<'s> From<ParsedMessage<'s>> for ParsedMessageOwned {
fn from(value: ParsedMessage<'s>) -> Self {
let ParsedMessage {
source,
separators,
segments,
} = value;
let source = source.to_string();
let segments = segments
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect();
ParsedMessageOwned {
source,
separators,
segments,
}
}
}
/// Results from locating a cursor within a message
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct LocatedData<'s> {
/// The (segment ID, segment ID repeat # (0-based), and segment) containing the cursor
pub segment: Option<(&'s str, usize, &'s Segment)>,
/// The (1-based field ID, field) containing the cursor
pub field: Option<(NonZeroUsize, &'s Field)>,
/// The (1-based repeat ID, repeat) containing the cursor
pub repeat: Option<(NonZeroUsize, &'s Repeat)>,
/// The (1-based component ID, component) containing the cursor
pub component: Option<(NonZeroUsize, &'s Component)>,
/// The (1-based sub-component ID, sub-component) containing the cursor
pub sub_component: Option<(NonZeroUsize, &'s SubComponent)>,
}
impl<'s> std::fmt::Display for LocatedData<'s> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(segment) = self.segment {
write!(f, "{}", segment.0)?;
} else {
return Ok(());
}
if let Some(field) = self.field {
write!(f, ".{}", field.0)?;
} else {
return Ok(());
}
if let Some(repeat) = self.repeat {
write!(f, "[{}]", repeat.0)?;
}
if let Some(component) = self.component {
write!(f, ".{}", component.0)?;
} else {
return Ok(());
}
if let Some(sub_component) = self.sub_component {
write!(f, ".{}", sub_component.0)?;
} else {
return Ok(());
}
Ok(())
}
}
impl<'s> ParsedMessage<'s> {
/// Parse a string to obtain the underlying message
pub fn parse(
source: &'s str,
lenient_segment_separators: bool,
) -> Result<ParsedMessage<'s>, ParseError> {
let (_, message) = crate::parser::parse_message(
crate::parser::Span::new(source),
lenient_segment_separators,
)?;
Ok(message)
}
/// Whether the message contains any of the given segment identifier (`MSH`, `PID`, `PV1`, etc)
pub fn has_segment<S: AsRef<str>>(&'s self, segment: S) -> bool {
self.segments.contains_key(segment.as_ref())
}
/// Access the first segment identified by `segment`
pub fn segment<S: AsRef<str>>(&'s self, segment: S) -> Option<&'s Segment> {
self.segments
.get(segment.as_ref())
.and_then(|seg| seg.get(0))
}
/// Return the number of times segments identified by `segment` are present in the message
pub fn segment_count<S: AsRef<str>>(&'s self, segment: S) -> usize {
self.segments
.get(segment.as_ref())
.map(|seg| seg.len())
.unwrap_or_default()
}
/// Get the 0-based nth segment identified by `segment` (i.e., if there were two `OBX` segments
/// and you wanted the second one, call `message.segment_n("OBX", 1)`)
pub fn segment_n<S: AsRef<str>>(&'s self, segment: S, n: usize) -> Option<&'s Segment> {
self.segments
.get(segment.as_ref())
.and_then(|seg| seg.get(n))
}
/// Mutable access to the 0-based nth segment identified by `segment` (i.e., if there were two `OBX` Segments
/// and you wanted the second one, call `message.segment_n_mut("OBX", 1)`)
pub fn segment_n_mut<S: AsRef<str>>(&mut self, segment: S, n: usize) -> Option<&mut Segment> {
self.segments
.get_mut(segment.as_ref())
.and_then(|seg| seg.get_mut(n))
}
/// Directly get the source (not yet decoded) for a given field, if it exists in the message. The
/// field is identified by the segment identifier, segment repeat identifier, and 1-based field
/// identifier.
///
/// # Examples
///
/// ```
/// # use hl7_parser::ParsedMessage;
/// # use std::num::NonZeroUsize;
/// let message = include_str!("../test_assets/sample_adt_a01.hl7");
/// let message = ParsedMessage::parse(&message, true).expect("can parse message");
///
/// let message_type = message.get_field_source(("MSH", 0), NonZeroUsize::new(9).unwrap());
/// assert_eq!(message_type.unwrap(), "ADT^A01");
/// ```
pub fn get_field_source<S: AsRef<str>>(
&'s self,
segment: (S, usize),
field: NonZeroUsize,
) -> Option<&'s str> {
let Some(seg) = self.segment_n(segment.0, segment.1) else {
return None;
};
seg.field(field).map(|f| f.source(self.source))
}
/// Get the field for a given field, if it exists in the message. The field
/// is identified by the segment identifier, segment repeat identifier, and 1-based field
/// identifier.
pub fn get_field<S: AsRef<str>>(
&'s self,
segment: (S, usize),
field: NonZeroUsize,
) -> Option<&'s Field> {
let Some(seg) = self.segment_n(segment.0, segment.1) else {
return None;
};
seg.field(field)
}
/// Directly get the source (not yet decoded) for a given field and repeat, if it exists in the message. The
/// field is identified by the segment identifier, segment repeat identifier, 1-based field identifier, and the repeat identifier
///
/// # Examples
///
/// ```
/// # use hl7_parser::ParsedMessage;
/// # use std::num::NonZeroUsize;
/// let message = include_str!("../test_assets/sample_adt_a04.hl7");
/// let message = ParsedMessage::parse(&message, true).expect("can parse message");
///
/// let allergy_reaction_2 = message.get_repeat_source(
/// ("AL1", 0),
/// NonZeroUsize::new(5).unwrap(),
/// NonZeroUsize::new(2).unwrap());
/// assert_eq!(allergy_reaction_2.unwrap(), "RASH");
/// ```
pub fn get_repeat_source<S: AsRef<str>>(
&'s self,
segment: (S, usize),
field: NonZeroUsize,
repeat: NonZeroUsize,
) -> Option<&'s str> {
let Some(seg) = self.segment_n(segment.0, segment.1) else {
return None;
};
seg.field(field)
.repeat(repeat)
.map(|r| r.source(self.source))
}
/// Directly get the repeat for a given field and repeat, if it exists in
/// the message. The field is identified by the segment identifier, segment
/// repeat identifier, 1-based field identifier, and the repeat identifier
pub fn get_repeat<S: AsRef<str>>(
&'s self,
segment: (S, usize),
field: NonZeroUsize,
repeat: NonZeroUsize,
) -> Option<&'s Repeat> {
let Some(seg) = self.segment_n(segment.0, segment.1) else {
return None;
};
seg.field(field).and_then(|f| f.repeat(repeat))
}
/// Directly get the source (not yet decoded) for a given component, if it exists in the message. The
/// component is identified by the segment identifier, segment repeat identifier, 1-based field
/// identifier, and 1-based component identifier
///
/// # Examples
///
/// ```
/// # use hl7_parser::ParsedMessage;
/// # use std::num::NonZeroUsize;
/// let message = include_str!("../test_assets/sample_adt_a01.hl7");
/// let message = ParsedMessage::parse(&message, true).expect("can parse message");
///
/// let trigger_event = message.get_component_source(
/// ("MSH", 0),
/// NonZeroUsize::new(9).unwrap(),
/// NonZeroUsize::new(1).unwrap(),
/// NonZeroUsize::new(2).unwrap());
/// assert_eq!(trigger_event.unwrap(), "A01");
/// ```
pub fn get_component_source<S: AsRef<str>>(
&'s self,
segment: (S, usize),
field: NonZeroUsize,
repeat: NonZeroUsize,
component: NonZeroUsize,
) -> Option<&'s str> {
let Some(seg) = self.segment_n(segment.0, segment.1) else {
return None;
};
seg.field(field)
.repeat(repeat)
.component(component)
.map(|c| c.source(self.source))
}
/// Directly get the component for a given component, if it exists in the message. The
/// component is identified by the segment identifier, segment repeat identifier, 1-based field
/// identifier, and 1-based component identifier
pub fn get_component<S: AsRef<str>>(
&'s self,
segment: (S, usize),
field: NonZeroUsize,
repeat: NonZeroUsize,
component: NonZeroUsize,
) -> Option<&'s Component> {
let Some(seg) = self.segment_n(segment.0, segment.1) else {
return None;
};
seg.field(field)
.and_then(|f| f.repeat(repeat))
.and_then(|r| r.component(component))
}
/// Directly get the source (not yet decoded) for a given sub-component, if it exists in the message.
/// The component is identified by the segment identifier, segment repeat identifier, 1-based field
/// identifier, 1-based component identifier, and 1-based sub-component identifier
///
/// # Examples
///
/// ```
/// # use hl7_parser::ParsedMessage;
/// # use std::num::NonZeroUsize;
/// let message = include_str!("../test_assets/sample_oru_r01_generic.hl7");
/// let message = ParsedMessage::parse(&message, true).expect("can parse message");
///
/// let universal_id = message.get_sub_component_source(
/// ("PID", 0),
/// NonZeroUsize::new(3).unwrap(),
/// NonZeroUsize::new(1).unwrap(),
/// NonZeroUsize::new(4).unwrap(),
/// NonZeroUsize::new(2).unwrap());
/// assert_eq!(universal_id.unwrap(), "1.2.840.114398.1.100");
/// ```
pub fn get_sub_component_source<S: AsRef<str>>(
&'s self,
segment: (S, usize),
field: NonZeroUsize,
repeat: NonZeroUsize,
component: NonZeroUsize,
sub_component: NonZeroUsize,
) -> Option<&'s str> {
let Some(seg) = self.segment_n(segment.0, segment.1) else {
return None;
};
seg.field(field)
.repeat(repeat)
.component(component)
.sub_component(sub_component)
.map(|s| s.source(self.source))
}
/// Directly get the sub-component for a given sub-component, if it exists in the message.
/// The component is identified by the segment identifier, segment repeat identifier, 1-based field
/// identifier, 1-based component identifier, and 1-based sub-component identifier
pub fn get_sub_component<S: AsRef<str>>(
&'s self,
segment: (S, usize),
field: NonZeroUsize,
repeat: NonZeroUsize,
component: NonZeroUsize,
sub_component: NonZeroUsize,
) -> Option<&'s SubComponent> {
let Some(seg) = self.segment_n(segment.0, segment.1) else {
return None;
};
seg.field(field)
.and_then(|f| f.repeat(repeat))
.and_then(|r| r.component(component))
.and_then(|c| c.sub_component(sub_component))
}
/// Locate a segment at the cursor position
///
/// # Arguments
///
/// * `cursor` - The cursor location (0-based character index of the original message)
///
/// # Returns
///
/// A tuple containing the HL7 segment identifier, 0-based segment repeat number and a
/// reference to the field. If the segment doesn't contain the cursor, returns `None`
pub fn segment_at_cursor(&'s self, cursor: usize) -> Option<(&'s str, usize, &'s Segment)> {
self.segments
.iter()
.find_map(|(id, segs)| segs.segment_at_cursor(cursor).map(|(n, seg)| (*id, n, seg)))
}
/// Deeply locate the cursor by returning the sub-component, component, field, and segment that
/// the cursor is located in (if any)
pub fn locate_cursor(&'s self, cursor: usize) -> LocatedData<'s> {
let segment = self.segment_at_cursor(cursor);
let field = segment.and_then(|(_, _, segment)| segment.field_at_cursor(cursor));
let multi_repeats = field.map(|(_, f)| f.repeats.len() > 1).unwrap_or_default();
let repeat = field.and_then(|(_, field)| field.repeat_at_cursor(cursor));
let component = repeat.and_then(|(_, repeat)| repeat.component_at_cursor(cursor));
let sub_component =
component.and_then(|(_, component)| component.sub_component_at_cursor(cursor));
LocatedData {
segment,
field,
repeat: if repeat.is_some() && multi_repeats {
repeat
} else {
None
},
component,
sub_component,
}
}
/// Query the message for a given segment, field, component, or sub-comonent.
///
/// # Arguments
///
/// * `query` - a [LocationQuery] targeting you want to access
///
/// # Returns
///
/// * [Result::Err] if the location query couldn't be parsed
/// * [Result::Ok] if the item location query could be parsed message
/// + [Option::Some] containing the item source if the queried item was found in the message
/// + [Option::None] if the queried item was _not_ found in the message
/// message
///
/// # Examples
///
/// ```
/// # use hl7_parser::ParsedMessage;
/// # use std::num::NonZeroUsize;
/// let message = include_str!("../test_assets/sample_adt_a01.hl7");
/// let message = ParsedMessage::parse(&message, true).expect("can parse message");
///
/// let trigger_event = message.query_value("MSH.9.2").expect("can parse location query");
/// assert_eq!(trigger_event, Some("A01"));
/// ```
pub fn query_value<Q, QErr>(&'s self, query: Q) -> Result<Option<&'s str>, QErr>
where
Q: TryInto<LocationQuery, Error = QErr>,
{
let LocationQuery {
segment,
field,
repeat,
component,
sub_component,
} = query.try_into()?;
let repeat = if repeat.is_none() && component.is_some() || sub_component.is_some() {
Some(NonZeroUsize::new(1).unwrap())
} else {
repeat
};
Ok(match (field, repeat, component, sub_component) {
(Some(f), Some(r), Some(c), Some(s)) => {
self.get_sub_component_source((segment, 0), f, r, c, s)
}
(Some(f), Some(r), Some(c), _) => self.get_component_source((segment, 0), f, r, c),
(Some(f), Some(r), _, _) => self.get_repeat_source((segment, 0), f, r),
(Some(f), _, _, _) => self.get_field_source((segment, 0), f),
_ => self.segment(segment).map(|seg| seg.source(self.source)),
})
}
/// Query the message for a given segment, field, component, or sub-comonent,
/// returning the range in the source string that the item occupies.
///
/// # Arguments
///
/// * `query` - a [LocationQuery] targeting you want to access
///
/// # Returns
///
/// * [Result::Err] if the location query couldn't be parsed
/// * [Result::Ok] if the item location query could be parsed message
/// + [Option::Some] containing the range in the source if the queried item was found in the message
/// + [Option::None] if the queried item was _not_ found in the message
/// message
///
/// # Examples
///
/// ```
/// # use hl7_parser::ParsedMessage;
/// # use std::num::NonZeroUsize;
/// let message = include_str!("../test_assets/sample_adt_a01.hl7");
/// let message = ParsedMessage::parse(&message, true).expect("can parse message");
///
/// let trigger_event = message.query("MSH.9.2").expect("can parse location query");
/// assert_eq!(trigger_event, Some(40..43));
/// ```
pub fn query<Q, QErr>(&self, query: Q) -> Result<Option<Range<usize>>, QErr>
where
Q: TryInto<LocationQuery, Error = QErr>,
{
let LocationQuery {
segment,
field,
repeat,
component,
sub_component,
} = query.try_into()?;
let repeat = if repeat.is_none() && component.is_some() || sub_component.is_some() {
Some(NonZeroUsize::new(1).unwrap())
} else {
repeat
};
Ok(match (field, repeat, component, sub_component) {
(Some(f), Some(r), Some(c), Some(s)) => self
.get_sub_component((segment, 0), f, r, c, s)
.map(|s| s.range.clone()),
(Some(f), Some(r), Some(c), _) => self
.get_component((segment, 0), f, r, c)
.map(|c| c.range.clone()),
(Some(f), Some(r), _, _) => {
self.get_repeat((segment, 0), f, r).map(|r| r.range.clone())
}
(Some(f), _, _, _) => self.get_field((segment, 0), f).map(|f| f.range.clone()),
_ => self.segment(segment).map(|seg| seg.range.clone()),
})
}
}
impl ParsedMessageOwned {
/// Parse a string to obtain the underlying message
pub fn parse<'s, S: ToString + 's>(
source: S,
lenient_segment_separators: bool,
) -> Result<ParsedMessageOwned, ParseError> {
let source = source.to_string();
let (_, message) = crate::parser::parse_message(
crate::parser::Span::new(&source),
lenient_segment_separators,
)?;
Ok(message.into())
}
/// Whether the message contains any of the given segment identifier (`MSH`, `PID`, `PV1`, etc)
pub fn has_segment<S: AsRef<str>>(&self, segment: S) -> bool {
self.segments.contains_key(segment.as_ref())
}
/// Access the first segment identified by `segment`
pub fn segment<S: AsRef<str>>(&self, segment: S) -> Option<&Segment> {
self.segments
.get(segment.as_ref())
.and_then(|seg| seg.get(0))
}
/// Mutable access to the first segment identified by `segment`
pub fn segment_mut<S: AsRef<str>>(&mut self, segment: S) -> Option<&mut Segment> {
self.segments
.get_mut(segment.as_ref())
.and_then(|seg| seg.get_mut(0))
}
/// Return the number of times segments identified by `segment` are present in the message
pub fn segment_count<S: AsRef<str>>(&self, segment: S) -> usize {
self.segments
.get(segment.as_ref())
.map(|seg| seg.len())
.unwrap_or_default()
}
/// Get the 0-based nth segment identified by `segment` (i.e., if there were two `OBX` segments
/// and you wanted the second one, call `message.segment_n("OBX", 1)`)
pub fn segment_n<S: AsRef<str>>(&self, segment: S, n: usize) -> Option<&Segment> {
self.segments
.get(segment.as_ref())
.and_then(|seg| seg.get(n))
}
/// Mutable access to the 0-based nth segment identified by `segment` (i.e., if there were two `OBX` Segments
/// and you wanted the second one, call `message.segment_n_mut("OBX", 1)`)
pub fn segment_n_mut<S: AsRef<str>>(&mut self, segment: S, n: usize) -> Option<&mut Segment> {
self.segments
.get_mut(segment.as_ref())
.and_then(|seg| seg.get_mut(n))
}
/// Directly get the source (not yet decoded) for a given field, if it exists in the message. The
/// field is identified by the segment identifier, segment repeat identifier, and 1-based field
/// identifier.
///
/// # Examples
///
/// ```
/// # use hl7_parser::ParsedMessageOwned;
/// # use std::num::NonZeroUsize;
/// let message = include_str!("../test_assets/sample_adt_a01.hl7");
/// let message = ParsedMessageOwned::parse(&message, true).expect("can parse message");
///
/// let message_type = message.get_field_source(("MSH", 0), NonZeroUsize::new(9).unwrap());
/// assert_eq!(message_type.unwrap(), "ADT^A01");
/// ```
pub fn get_field_source<S: AsRef<str>>(
&self,
segment: (S, usize),
field: NonZeroUsize,
) -> Option<&str> {
let Some(seg) = self.segment_n(segment.0, segment.1) else {
return None;
};
seg.field(field).map(|f| f.source(self.source.as_str()))
}
/// Get the field for a given field, if it exists in the message. The field
/// is identified by the segment identifier, segment repeat identifier, and 1-based field
/// identifier.
pub fn get_field<S: AsRef<str>>(
&self,
segment: (S, usize),
field: NonZeroUsize,
) -> Option<&Field> {
let Some(seg) = self.segment_n(segment.0, segment.1) else {
return None;
};
seg.field(field)
}
/// Get a mutable reference to a field for a given field, if it exists in the message. The field
/// is identified by the segment identifier, segment repeat identifier, and 1-based field
/// identifier.
pub fn get_field_mut<S: AsRef<str>>(
&mut self,
segment: (S, usize),
field: NonZeroUsize,
) -> Option<&mut Field> {
let Some(seg) = self.segment_n_mut(segment.0, segment.1) else {
return None;
};
seg.field_mut(field)
}
/// Directly get the source (not yet decoded) for a given field and repeat, if it exists in the message. The
/// field is identified by the segment identifier, segment repeat identifier, 1-based field identifier, and the repeat identifier
///
/// # Examples
///
/// ```
/// # use hl7_parser::ParsedMessageOwned;
/// # use std::num::NonZeroUsize;
/// let message = include_str!("../test_assets/sample_adt_a04.hl7");
/// let message = ParsedMessageOwned::parse(&message, true).expect("can parse message");
///
/// let allergy_reaction_2 = message.get_repeat_source(
/// ("AL1", 0),
/// NonZeroUsize::new(5).unwrap(),
/// NonZeroUsize::new(2).unwrap());
/// assert_eq!(allergy_reaction_2.unwrap(), "RASH");
/// ```
pub fn get_repeat_source<S: AsRef<str>>(
&self,
segment: (S, usize),
field: NonZeroUsize,
repeat: NonZeroUsize,
) -> Option<&str> {
let Some(seg) = self.segment_n(segment.0, segment.1) else {
return None;
};
seg.field(field)
.repeat(repeat)
.map(|r| r.source(self.source.as_str()))
}
/// Directly get the repeat for a given field and repeat, if it exists in
/// the message. The field is identified by the segment identifier, segment
/// repeat identifier, 1-based field identifier, and the repeat identifier
pub fn get_repeat<S: AsRef<str>>(
&self,
segment: (S, usize),
field: NonZeroUsize,
repeat: NonZeroUsize,
) -> Option<&Repeat> {
let Some(seg) = self.segment_n(segment.0, segment.1) else {
return None;
};
seg.field(field).and_then(|f| f.repeat(repeat))
}
/// Get a mutable reference to the repeat for a given field and repeat, if it exists in
/// the message. The field is identified by the segment identifier, segment
/// repeat identifier, 1-based field identifier, and the repeat identifier
pub fn get_repeat_mut<S: AsRef<str>>(
&mut self,
segment: (S, usize),
field: NonZeroUsize,
repeat: NonZeroUsize,
) -> Option<&mut Repeat> {
let Some(seg) = self.segment_n_mut(segment.0, segment.1) else {
return None;
};
seg.field_mut(field).and_then(|f| f.repeat_mut(repeat))
}
/// Directly get the source (not yet decoded) for a given component, if it exists in the message. The
/// component is identified by the segment identifier, segment repeat identifier, 1-based field
/// identifier, and 1-based component identifier
///
/// # Examples
///
/// ```
/// # use hl7_parser::ParsedMessageOwned;
/// # use std::num::NonZeroUsize;
/// let message = include_str!("../test_assets/sample_adt_a01.hl7");
/// let message = ParsedMessageOwned::parse(&message, true).expect("can parse message");
///
/// let trigger_event = message.get_component_source(
/// ("MSH", 0),
/// NonZeroUsize::new(9).unwrap(),
/// NonZeroUsize::new(1).unwrap(),
/// NonZeroUsize::new(2).unwrap());
/// assert_eq!(trigger_event.unwrap(), "A01");
/// ```
pub fn get_component_source<S: AsRef<str>>(
&self,
segment: (S, usize),
field: NonZeroUsize,
repeat: NonZeroUsize,
component: NonZeroUsize,
) -> Option<&str> {
let Some(seg) = self.segment_n(segment.0, segment.1) else {
return None;
};
seg.field(field)
.repeat(repeat)
.component(component)
.map(|c| c.source(self.source.as_str()))
}
/// Directly get the component for a given component, if it exists in the message. The
/// component is identified by the segment identifier, segment repeat identifier, 1-based field
/// identifier, and 1-based component identifier
pub fn get_component<S: AsRef<str>>(
&self,
segment: (S, usize),
field: NonZeroUsize,
repeat: NonZeroUsize,
component: NonZeroUsize,
) -> Option<&Component> {
let Some(seg) = self.segment_n(segment.0, segment.1) else {
return None;
};
seg.field(field)
.and_then(|f| f.repeat(repeat))
.and_then(|r| r.component(component))
}
/// Get a mutable reference to a component for a given component, if it exists in the message. The
/// component is identified by the segment identifier, segment repeat identifier, 1-based field
/// identifier, and 1-based component identifier
pub fn get_component_mut<S: AsRef<str>>(
&mut self,
segment: (S, usize),
field: NonZeroUsize,
repeat: NonZeroUsize,
component: NonZeroUsize,
) -> Option<&mut Component> {
let Some(seg) = self.segment_n_mut(segment.0, segment.1) else {
return None;
};
seg.field_mut(field)
.and_then(|f| f.repeat_mut(repeat))
.and_then(|r| r.component_mut(component))
}
/// Directly get the source (not yet decoded) for a given sub-component, if it exists in the message.
/// The component is identified by the segment identifier, segment repeat identifier, 1-based field
/// identifier, 1-based component identifier, and 1-based sub-component identifier
///
/// # Examples
///
/// ```
/// # use hl7_parser::ParsedMessageOwned;
/// # use std::num::NonZeroUsize;
/// let message = include_str!("../test_assets/sample_oru_r01_generic.hl7");
/// let message = ParsedMessageOwned::parse(message, true).expect("can parse message");
///
/// let universal_id = message.get_sub_component_source(
/// ("PID", 0),
/// NonZeroUsize::new(3).unwrap(),
/// NonZeroUsize::new(1).unwrap(),
/// NonZeroUsize::new(4).unwrap(),
/// NonZeroUsize::new(2).unwrap());
/// assert_eq!(universal_id.unwrap(), "1.2.840.114398.1.100");
/// ```
pub fn get_sub_component_source<S: AsRef<str>>(
&self,
segment: (S, usize),
field: NonZeroUsize,
repeat: NonZeroUsize,
component: NonZeroUsize,
sub_component: NonZeroUsize,
) -> Option<&str> {
let Some(seg) = self.segment_n(segment.0, segment.1) else {
return None;
};
seg.field(field)
.repeat(repeat)
.component(component)
.sub_component(sub_component)
.map(|s| s.source(self.source.as_str()))
}
/// Directly get the sub-component for a given sub-component, if it exists in the message.
/// The component is identified by the segment identifier, segment repeat identifier, 1-based field
/// identifier, 1-based component identifier, and 1-based sub-component identifier
pub fn get_sub_component<S: AsRef<str>>(
&self,
segment: (S, usize),
field: NonZeroUsize,
repeat: NonZeroUsize,
component: NonZeroUsize,
sub_component: NonZeroUsize,
) -> Option<&SubComponent> {
let Some(seg) = self.segment_n(segment.0, segment.1) else {
return None;
};
seg.field(field)
.and_then(|f| f.repeat(repeat))
.and_then(|r| r.component(component))
.and_then(|c| c.sub_component(sub_component))
}
/// Get a mutable reference to the sub-component for a given sub-component, if it exists in the message.
/// The component is identified by the segment identifier, segment repeat identifier, 1-based field
/// identifier, 1-based component identifier, and 1-based sub-component identifier
pub fn get_sub_component_mut<S: AsRef<str>>(
&mut self,
segment: (S, usize),
field: NonZeroUsize,
repeat: NonZeroUsize,
component: NonZeroUsize,
sub_component: NonZeroUsize,
) -> Option<&mut SubComponent> {
let Some(seg) = self.segment_n_mut(segment.0, segment.1) else {
return None;
};
seg.field_mut(field)
.and_then(|f| f.repeat_mut(repeat))
.and_then(|r| r.component_mut(component))
.and_then(|c| c.sub_component_mut(sub_component))
}
/// Locate a segment at the cursor position
///
/// # Arguments
///
/// * `cursor` - The cursor location (0-based character index of the original message)
///
/// # Returns
///
/// A tuple containing the HL7 segment identifier, 0-based segment repeat number and a
/// reference to the field. If the segment doesn't contain the cursor, returns `None`
pub fn segment_at_cursor(&self, cursor: usize) -> Option<(&str, usize, &Segment)> {
self.segments.iter().find_map(|(id, segs)| {
segs.segment_at_cursor(cursor)
.map(|(n, seg)| (id.as_str(), n, seg))
})
}
/// Deeply locate the cursor by returning the sub-component, component, field, and segment that
/// the cursor is located in (if any)
pub fn locate_cursor(&self, cursor: usize) -> LocatedData {
let segment = self.segment_at_cursor(cursor);
let field = segment.and_then(|(_, _, segment)| segment.field_at_cursor(cursor));
let repeat = field.and_then(|(_, field)| field.repeat_at_cursor(cursor));
let component = repeat.and_then(|(_, repeat)| repeat.component_at_cursor(cursor));
let sub_component =
component.and_then(|(_, component)| component.sub_component_at_cursor(cursor));
LocatedData {
segment,
field,
repeat,
component,
sub_component,
}
}
/// Query the message for a given segment, field, component, or sub-comonent.
///
/// # Arguments
///
/// * `query` - a [LocationQuery] targeting you want to access
///
/// # Returns
///
/// * [Result::Err] if the location query couldn't be parsed
/// * [Result::Ok] if the item location query could be parsed message
/// + [Option::Some] containing the item source if the queried item was found in the message
/// + [Option::None] if the queried item was _not_ found in the message
///
/// # Examples
///
/// ```
/// # use hl7_parser::ParsedMessageOwned;
/// # use std::num::NonZeroUsize;
/// let message = include_str!("../test_assets/sample_adt_a01.hl7");
/// let message = ParsedMessageOwned::parse(message, true).expect("can parse message");
///
/// let trigger_event = message.query_value("MSH.9.2").expect("can parse location query");
/// assert_eq!(trigger_event, Some("A01"));
/// ```
pub fn query_value<Q, QErr>(&self, query: Q) -> Result<Option<&str>, QErr>
where
Q: TryInto<LocationQuery, Error = QErr>,
{
let LocationQuery {
segment,
field,
repeat,
component,
sub_component,
} = query.try_into()?;
let repeat = if repeat.is_none() && component.is_some() || sub_component.is_some() {
Some(NonZeroUsize::new(1).unwrap())
} else {
repeat
};
Ok(match (field, repeat, component, sub_component) {
(Some(f), Some(r), Some(c), Some(s)) => {
self.get_sub_component_source((segment, 0), f, r, c, s)
}
(Some(f), Some(r), Some(c), _) => self.get_component_source((segment, 0), f, r, c),
(Some(f), Some(r), _, _) => self.get_repeat_source((segment, 0), f, r),
(Some(f), _, _, _) => self.get_field_source((segment, 0), f),
_ => self
.segment(segment)
.map(|seg| seg.source(self.source.as_str())),
})
}
/// Query the message for a given segment, field, component, or sub-comonent,
/// returning the range in the source string that the item occupies.
///
/// # Arguments
///
/// * `query` - a [LocationQuery] targeting you want to access
///
/// # Returns
///
/// * [Result::Err] if the location query couldn't be parsed
/// * [Result::Ok] if the item location query could be parsed message
/// + [Option::Some] containing the item source if the queried item was found in the message
/// + [Option::None] if the queried item was _not_ found in the message
///
/// # Examples
///
/// ```
/// # use hl7_parser::ParsedMessageOwned;
/// # use std::num::NonZeroUsize;
/// let message = include_str!("../test_assets/sample_adt_a01.hl7");
/// let message = ParsedMessageOwned::parse(message, true).expect("can parse message");
///
/// let trigger_event = message.query("MSH.9.2").expect("can parse location query");
/// assert_eq!(trigger_event, Some(40..43));
/// ```
pub fn query<Q, QErr>(&self, query: Q) -> Result<Option<Range<usize>>, QErr>
where
Q: TryInto<LocationQuery, Error = QErr>,
{
let LocationQuery {
segment,
field,
repeat,
component,
sub_component,
} = query.try_into()?;
let repeat = if repeat.is_none() && component.is_some() || sub_component.is_some() {
Some(NonZeroUsize::new(1).unwrap())
} else {
repeat
};
Ok(match (field, repeat, component, sub_component) {
(Some(f), Some(r), Some(c), Some(s)) => self
.get_sub_component((segment, 0), f, r, c, s)
.map(|s| s.range.clone()),
(Some(f), Some(r), Some(c), _) => self
.get_component((segment, 0), f, r, c)
.map(|c| c.range.clone()),
(Some(f), Some(r), _, _) => {
self.get_repeat((segment, 0), f, r).map(|r| r.range.clone())
}
(Some(f), _, _, _) => self.get_field((segment, 0), f).map(|f| f.range.clone()),
_ => self.segment(segment).map(|seg| seg.range.clone()),
})
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn can_locate_cursor() {
let cursor = 26;
let message = include_str!("../test_assets/sample_adt_a01.hl7");
let message = ParsedMessage::parse(message, true).expect("can parse message");
let (id, n, seg) = message
.segment_at_cursor(cursor)
.expect("can get segment at cursor");
assert_eq!(id, "MSH");
assert_eq!(n, 0);
let (n, _field) = seg
.field_at_cursor(cursor)
.expect("can get field at cursor");
assert_eq!(n, NonZeroUsize::new(7).unwrap());
let cursor = 0x458;
let (id, n, seg) = message
.segment_at_cursor(cursor)
.expect("can get segment at cursor");
assert_eq!(id, "IN1");
assert_eq!(n, 1);
let (n, field) = seg
.field_at_cursor(cursor)
.expect("can get field at cursor");
assert_eq!(n, NonZeroUsize::new(5).unwrap());
let (n, repeat) = field
.repeat_at_cursor(cursor)
.expect("can get repeat at cursor");
assert_eq!(n.get(), 1);
let (n, component) = repeat
.component_at_cursor(cursor)
.expect("can get component at cursor");
assert_eq!(n, NonZeroUsize::new(3).unwrap());
assert_eq!(component.source(message.source), "HOLLYWOOD");
let message = include_str!("../test_assets/sample_adt_a04.hl7");
let message = ParsedMessage::parse(message, true).expect("can parse message");
let cursor = 0x1cc;
let (id, n, seg) = message
.segment_at_cursor(cursor)
.expect("can get segment at cursor");
assert_eq!(id, "AL1");
assert_eq!(n, 0);
let (n, field) = seg
.field_at_cursor(cursor)
.expect("can get field at cursor");
assert_eq!(n, NonZeroUsize::new(5).unwrap());
let (n, repeat) = field
.repeat_at_cursor(cursor)
.expect("can get repeat at cursor");
assert_eq!(n.get(), 2);
assert_eq!(repeat.source(message.source), "RASH");
}
#[test]
fn can_locate_cursor_at_empty_fields() {
let message = include_str!("../test_assets/sample_adt_a01.hl7");
let message = ParsedMessage::parse(message, true).expect("can parse message");
let location = message.locate_cursor(19);
assert!(location.segment.is_some());
assert!(location.field.is_some());
assert!(location.component.is_none());
assert!(location.sub_component.is_none());
}
#[test]
fn can_display_hl7_path() {
let cursor = 0x458;
let message = include_str!("../test_assets/sample_adt_a01.hl7");
let message = ParsedMessage::parse(message, true).expect("can parse message");
let location = message.locate_cursor(cursor);
let location = format!("{location}");
assert_eq!(location, "IN1.5.3.1");
let cursor = 0x1cc;
let message = include_str!("../test_assets/sample_adt_a04.hl7");
let message = ParsedMessage::parse(message, true).expect("can parse message");
let location = message.locate_cursor(cursor);
let location = format!("{location}");
assert_eq!(location, "AL1.5[2].1.1");
}
#[test]
fn can_create_owned_version() {
let raw_message = include_str!("../test_assets/sample_adt_a01.hl7");
let message = ParsedMessage::parse(raw_message, true).expect("can parse message");
let message_from = ParsedMessageOwned::from(message);
let message_direct =
ParsedMessageOwned::parse(raw_message, true).expect("can parse message");
assert_eq!(message_from, message_direct);
}
#[test]
fn has_a_not_terrible_error_message() {
assert_eq!(
ParsedMessage::parse("MSH|^~\\&$", false)
.expect_err("ParsedMessage parsing to fail")
.to_string()
.as_str(),
"ParsedMessage parsing failed at position 8 (line 1 column 9): `$`"
);
}
#[test]
fn message_and_message_buf_have_the_same_errors() {
let err =
ParsedMessage::parse("MSH|^~\\&$", false).expect_err("ParsedMessage parsing to fail");
let err_buf = ParsedMessageOwned::parse("MSH|^~\\&$", false)
.expect_err("ParsedMessage parsing to fail");
assert_eq!(err, err_buf);
assert_eq!(err.to_string(), err_buf.to_string());
}
}