Package hl7 provides a parser for HL7 version 2.x messages. The parser reads HL7v2 messages encoded in the ER7 (pipe-delimited) format and returns a structured representation. It has zero external dependencies, requires Go 1.23+, and is safe for concurrent use after parsing. HL7v2 messages have a hierarchical structure: Delimiter characters are extracted from each message's MSH segment header and are not assumed to be the standard set (|^~\&), although that is typical. ParseMessage copies the input, extracts delimiters from the MSH header, merges any ADD continuation segments into their preceding segments per HL7v2.5.1 Section 2.5.2, and splits the message into segments by \r. This is the only phase that allocates. All deeper access — fields, repetitions, components, and subcomponents — is performed by scanning the segment's raw bytes on each call. No parsed results are cached; the sub-message types (Field, Repetition, Component, Subcomponent) are lightweight value types holding only a []byte slice and a Delimiters struct. Escape processing is deferred until String() is called. A consumer that reads only MSH-9 (message type) never pays the cost of scanning OBX observation segments. Get retrieves values using terser-style location strings and returns a Value. ParseLocation parses the string into a Location struct, and Location.String implements the inverse. Get returns a zero Value when the location is invalid or the value is not present — consistent with how Field(n), Rep(n), and Component(n) return zero values for out-of-range indices rather than errors. Field values in non-UTF-8 charsets (e.g. Latin-1 / ISO 8859-1 declared in MSH-18) can be decoded with DecodeString. A ValueMapper is a func([]byte) ([]byte, error) that converts post-unescape bytes to UTF-8. DecodeString is available on Value, Field, Repetition, Component, and Subcomponent: When decode is nil, DecodeString behaves identically to String() with no extra allocation. Unescape always runs before the mapper. The \C..\ and \M..\ charset escape sequences are passed through verbatim by Unescape; a sophisticated ValueMapper may parse them, but a simple byte-level mapper will treat them as-is. Segments returns a []Segment slice. Filter by type with seg.Type(): Navigate the hierarchy using Field, Rep, Component, and SubComponent: Index conventions: Field is 0-based (0 = segment type, 1+ = fields). Rep is 0-based. Component and SubComponent are 1-based. Out-of-range access returns zero values, enabling chained access without nil checks. Count methods are available at each level: FieldCount, RepetitionCount, ComponentCount, and SubComponentCount. Reader modes: ModeAuto (default, detects framing), ModeMLLP (strict MLLP), ModeRaw (MSH-boundary detection). ReadMessage returns one parsed message at a time; EachMessage iterates until EOF. Without WithMLLP, messages are written as raw bytes with a trailing \r. With WithMLLP, messages are wrapped in 0x0B...0x1C 0x0D framing. Transform applies changes to a message and returns a new Message, leaving the original unmodified: Field-level change constructors: Replace sets a value, Null sets the HL7 null (""), Omit clears a field, Move copies src to dst then clears src, Copy copies src to dst while preserving the source, MapValue applies a ValueMapper to a single location, and MapAllValues applies a ValueMapper to every leaf in the message (except MSH-1 and MSH-2). The mapper receives unescaped bytes; its output is re-escaped before storage. Segment-level change constructors add, remove, or reorder entire segments: DeleteSegment and DeleteAllSegments are no-ops when the target is absent; both return ErrCannotDeleteMSH if given "MSH". InsertSegmentAfter and InsertSegmentBefore return ErrSegmentNotFound when the reference segment is absent. Segment-level and field-level changes compose freely in one call. TransformWith additionally re-encodes all delimiters to a new set: MessageBuilder constructs messages from scratch: Use WithDelimiters to override the default delimiter set. SetNull sets a field to the HL7 null value. The builder is reusable after Build — subsequent Set calls modify its state. Ack creates an acknowledgment message in response to a parsed message: AckCode constants: AA, AE, AR (application level), CA, CE, CR (commit level). Options: WithText sets MSA-3 for error context, WithTimestamp overrides the default time.Now for MSH-7, and WithErrors adds ERR segments from validation issues. The ACK copies delimiters and swaps sender/receiver fields from the original MSH. WithErrors accepts a slice of Issue (from Validate) and produces one ERR segment per issue with error location (ERR-2), severity (ERR-4), application error code (ERR-5), and diagnostic information (ERR-7): Validate checks a parsed message against a user-provided Schema: Schema has four optional maps (Messages, Segments, DataTypes, Tables) plus a Checks slice for message-level custom validators. Only populated maps trigger validation. Schema types support JSON/YAML/TOML struct tags. Validation runs in three phases: structure (segment presence, order, cardinality via MessageDef), content (field presence, length, format, table values via SegmentDef/DataTypeDef/TableDef, plus FieldCheckFunc and SegmentCheckFunc validators), and custom checks (MessageCheckFunc from schema.Checks for cross-segment business rules). Concatenate reassembles multi-page query responses. When a server splits a large response across several messages using DSC (Continuation) segments, call Concatenate to merge them in order: Concatenate strips the trailing DSC segment from the receiver and the leading MSH segment from the argument, then returns a new Message containing the remaining segments. The DSC-1 continuation pointer is not interpreted; the caller is responsible for retrieving subsequent pages. ParseBatch parses a BHS/BTS-wrapped group of messages: ParseFile parses an FHS/FTS-wrapped file containing batches: Both are tolerant: header and trailer segments are optional. Escape replaces delimiter characters in data with HL7 escape sequences. Unescape resolves escape sequences back to literal values. Both have a zero-allocation fast path when no escaping is needed. Escape processing is deferred — Unescape runs only when String() is called, not during parsing. Bytes() returns raw data without escape processing. Per the HL7 specification, there is a distinction between empty and null fields: Use IsNull() and IsEmpty() to distinguish these cases; HasValue() returns true when neither empty nor null. All four hierarchy types (Field, Repetition, Component, Subcomponent) as well as Value share these methods. Parse-time errors use sentinel errors (ErrMessageTooShort, ErrNoMSHSegment, ErrInvalidDelimiter, etc.) that can be checked with errors.Is. ParseError wraps a sentinel with position and context for detailed diagnostics. Access-time methods (Field, Rep, Component, SubComponent) return zero values for out-of-range indices rather than errors, enabling ergonomic chained access. Validate never returns an error — it returns a *ValidationResult containing a Valid bool and a slice of Issue structs with Severity, Location, Code, and Description. See the examples/ directory for runnable programs demonstrating end-to-end workflows including stream reading, validation, transformation, and writing.