# `HL7v2.Parser`
[🔗](https://github.com/Balneario-de-Cofrentes/hl7v2/blob/v3.10.1/lib/hl7v2/parser.ex#L1)

Parses HL7v2 messages into raw representation with canonical round-trip fidelity.

The parser splits the message into segments, fields, repetitions, components,
and sub-components using the delimiters declared in the MSH segment header.
No type coercion or validation is performed. Line endings are normalized to CR
and a trailing CR is always present, so `parse(text) |> encode()` produces the
canonical wire form (which may differ from the input only in line-ending
normalization).

## MSH-1/MSH-2 Special Handling

MSH-1 (field separator) and MSH-2 (encoding characters) are not regular
delimited fields. The parser handles them as special cases:

- MSH-1 is stored as a single-byte binary (the field separator character)
- MSH-2 is stored as a 4- or 5-character literal string (encoding characters)
- Remaining MSH fields start at field index 2 (MSH-3 = index 2)

## Examples

    iex> {:ok, msg} = HL7v2.Parser.parse("MSH|^~\\&|SEND|FAC||RCV||20240101||ADT^A01|123|P|2.5\r")
    iex> msg.type
    {"ADT", "A01"}
    iex> length(msg.segments)
    1

# `parse`

```elixir
@spec parse(
  binary(),
  keyword()
) :: {:ok, HL7v2.RawMessage.t() | HL7v2.TypedMessage.t()} | {:error, term()}
```

Parses an HL7v2 message binary into a `RawMessage` struct.

## Options

- `:mode` — `:raw` (default) or `:typed` for parsed segment structs.
- `:copy` — `true` to copy all parsed binaries (prevents GC reference to original
  message binary). Use when storing parsed messages long-term. Default `false`.

Returns `{:ok, raw_message}` or `{:error, reason}`.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
