hl7probe 0.8.0

Read and check HL7 v2 messages: a library and a command-line tool
Documentation
//! Read and check HL7 v2 messages.
//!
//! A message is decomposed into named fields and checked against the HL7
//! dictionary: required fields, data types, code tables and cross-field
//! consistency. Parsing borrows the text it was given rather than copying it,
//! so a message costs a few hundred bytes on top of the string it came from.
//!
//! ```
//! let text = "MSH|^~\\&|HIS|MERCY|LIS|LAB|20240115143200||ADT^A01|MSG1|P|2.5.1\r\
//!             PID|1||123456^^^MERCY^MR||Smith^John||19850312|M\r";
//!
//! let message = hl7probe::parse(text)?;
//! assert_eq!(message.version(), "2.5.1");
//! assert_eq!(message.type_label(), "ADT^A01");
//!
//! // PID-5.1 is the patient's family name.
//! let pid = message.first("PID").expect("the message has a PID");
//! assert_eq!(pid.comp(5, 1), "Smith");
//!
//! let report = hl7probe::validate(&message);
//! println!("{} errors, {} warnings", report.errors(), report.warnings());
//! # Ok::<(), hl7probe::ParseError>(())
//! ```
//!
//! Messages borrow the text they were read from, so keep it alive for as long
//! as the [`Message`]. Use [`parser::split_messages`] and
//! [`parser::parse_message`] directly to walk a file holding several messages.

pub mod datetime;
pub mod parser;
pub mod spec;
pub mod validate;

// The command line's own presentation, not part of the library API.
mod render;
mod text;
mod tui;
mod view;

#[doc(hidden)]
pub mod cli;

pub use parser::{Component, Field, Message, ParseError, Repetition, Segment, Separators};
pub use validate::{Category, Finding, Report, Severity};

/// Parses the first message in `text`.
///
/// Leading batch wrappers and MLLP framing bytes are skipped, and CR, LF or
/// CRLF line endings are all accepted. For a file holding several messages,
/// use [`parser::split_messages`].
///
/// # Errors
///
/// Returns [`ParseError`] when `text` holds no MSH segment, or when the first
/// message's MSH does not declare a usable set of delimiters.
pub fn parse(text: &str) -> Result<Message<'_>, ParseError> {
    let (raws, _notes) = parser::split_messages(text);
    let Some(first) = raws.first() else {
        return Err(ParseError::no_message());
    };
    parser::parse_message(first)
}

/// Checks a parsed message against the HL7 dictionary.
#[must_use]
pub fn validate(message: &Message<'_>) -> Report {
    validate::validate(message)
}

#[cfg(test)]
mod tests {
    use super::{parse, validate, ParseError, Severity};

    const ADT: &str = "MSH|^~\\&|HIS|MERCY|LIS|LAB|20240115143200||ADT^A01|MSG1|P|2.5.1\r\
                       EVN|A01|20240115143200\r\
                       PID|1||123456^^^MERCY^MR||Smith^John||19850312|M\r\
                       PV1|1|I|ER^101^A\r";

    #[test]
    fn parse_reads_the_first_message() {
        let message = parse(ADT).expect("the fixture parses");
        assert_eq!(message.version(), "2.5.1");
        assert_eq!(message.type_label(), "ADT^A01");
        assert_eq!(message.control_id(), "MSG1");
        assert_eq!(message.segments.len(), 4);
        assert_eq!(
            message.first("PID").expect("PID is present").comp(5, 1),
            "Smith"
        );
    }

    #[test]
    fn parse_takes_the_first_of_several() {
        let batch = format!("{ADT}{}", ADT.replace("MSG1", "MSG2"));
        assert_eq!(parse(&batch).expect("parses").control_id(), "MSG1");
    }

    #[test]
    fn parse_rejects_text_that_holds_no_message() {
        for text in ["", "not hl7 at all", "PID|1||x\r"] {
            let error = parse(text).expect_err("there is no message here");
            assert!(error.to_string().contains("MSH"), "{error}");
        }
    }

    #[test]
    fn parse_rejects_a_message_whose_delimiters_are_unusable() {
        let error = parse("MSHzzzz\rPID|1\r").expect_err("z cannot be a separator");
        assert!(error.to_string().contains("separator"), "{error}");
    }

    /// The error type carries a line number and composes with `?`.
    #[test]
    fn parse_errors_are_std_errors() {
        fn read(text: &str) -> Result<String, Box<dyn std::error::Error>> {
            Ok(parse(text)?.type_label())
        }
        assert_eq!(read(ADT).expect("ok"), "ADT^A01");
        assert!(read("nothing").is_err());

        let error: ParseError = parse("MSHzzzz\r").expect_err("unusable");
        assert_eq!(error.line, 1);
        assert!(!error.message.is_empty());
    }

    #[test]
    fn validate_reports_on_a_parsed_message() {
        let clean = validate(&parse(ADT).expect("parses"));
        assert_eq!(clean.errors(), 0, "{:?}", clean.findings);

        // A date that does not exist, and no PV1 at all.
        let broken = ADT
            .replace("19850312", "19850332")
            .replace("PV1|1|I|ER^101^A\r", "");
        let report = validate(&parse(&broken).expect("still parses"));
        assert!(report.errors() > 0);
        assert_eq!(report.worst(), Some(Severity::Error));
        assert!(
            report
                .findings
                .iter()
                .any(|f| f.location == "PID-7" && f.severity == Severity::Error),
            "{:?}",
            report.findings
        );
    }
}