diff --git a/.gitignore b/.gitignore
index 6873570..c86de22 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,3 +3,5 @@
perf.*
*.svg
Cargo.lock
+.ignore
+*.failed
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d07cbf0..3878127 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,238 +1,484 @@
-mail-parser 0.11.9
-================================
+# Change Log
+
+All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/).
+
+## [1.0.0] - Unreleased
+
+A rewrite of the parser for performance, with a new read-only API. Breaking changes are listed under Changed and Removed; the table at the end of this entry maps the 0.11 API to 1.0.
+
+### Added
+- Bodies are decoded on access: `MessagePart::decoded()`, `decode_into()`, `decoded_len()` (measures base64 and quoted-printable without decoding), `text()`, `text_into()` and `text_prefix()` (decodes only what the first characters need).
+- `MessagePart::decoded_checked()` and `text_checked()` also return the `DecodeProblems` found while decoding (malformed base64 or quoted-printable, unknown transfer encoding, unknown charset, sequences not valid in the charset), which is the RFC 8621 `isEncodingProblem` flag.
+- `MessageRef`, a view of the root message or of a nested message, with `id()`, `root_part()`, `container()`, `source()`, `source_bytes()`, `raw()`, `parts()`, the body lists and the header getters; `Message::root()` and `Message::messages()`.
+- Access to MIME boundaries (#127): `MessagePart::boundary()`, `MessagePart::delimiter()` and `Message::part_by_boundary()`, and the raw bytes of a part with `raw()`, `raw_headers()` and `raw_body()`, which exclude the line break before the next delimiter as RFC 2046 defines the body part.
+- Part roles (#107): `MessagePart::role()` (`PartRole`) gives every part exactly one role, and `MessageRef::other_parts()` returns the parts in no list.
+- `MessageRef::has_attachments()`, the RFC 8621 `hasAttachment` rule: an attachment without `Content-Disposition: inline`.
+- `MessagePart::html_utf8()` and `strip_charset_meta()` (#109): the HTML with its `` charset declarations rewritten to UTF-8, looking only before `
` that owns its input, and `MessageParser::parse_with()` with `MessageBuffers` and `Message::into_buffers()` reuses the storage of one message for the next. `MessageBuffers::shrink_to(max_bytes)` frees that storage when it exceeds `max_bytes`; otherwise the buffers keep the capacity of the largest message parsed with them.
+- `MessageParser::header()` sets the form of one header field and `unknown_headers()` the form of unknown fields; `max_depth()`, `max_parts()` and `max_encoded_nesting()` set the limits (64, 10,000 and 3 by default). After the part limit, the rest of the input stays in the part flagged `LIMIT_REACHED`: the last part when it is a leaf of the innermost open multipart, else that multipart, or the `message/rfc822` part whose nested message had no part yet; the containers left open are not flagged `UNTERMINATED`.
+- `HeaderName::key()` resolves a name once into a `HeaderKey`, for `Headers::all_key()` and `Headers::get_key()`, which skip the name lookup that `all()` and `get()` do on every call.
+- 112 header names from Stalwart's metadata list are `HeaderName` variants: `X-Mailer`, `User-Agent`, `Precedence`, `X-Priority`, the `X-MS-Exchange`, `X-Google` and `X-GitHub` fields and others.
+- `Charset`, with `from_label()`, `decode()`, `decode_owned()` and `decode_append()`, and `decoders::charsets::decode()` and `decode_append()`.
+- `PartId` and `MessageId`, and `From for u8`.
+- Value equality for `HeaderValue`, `TextList`, `AddressList`, `ContentType`, `Received` and `ParsedValue`; `Debug` output that shows the content of the views; `Debug` for the mailbox iterators. `Message`, `MessageParser` and the views are `Send + Sync`, and `Message<'x>` is covariant in `'x`.
+
+### Changed
+- The parser was rewritten for performance: SIMD kernels find boundaries and header fields (NEON, AVX2 and SSE2, `memchr` on other targets), the header field parsers work on bounded slices, a message is stored in a handful of flat vectors whatever its size, and bodies are decoded only on access, through the SIMD codecs of encodify. See the README for measurements.
+- New dependencies: `memchr`, `simdutf8` and `encodify`, next to `hashify`; `encoding_rs` and `serde` stay optional. `unsafe` code is used in the SIMD kernels and in the audited UTF-8 module, whose two functions turn bytes already validated as UTF-8 into `str` and `String`: string spans validated during the parse, and decoded text bodies validated with simdutf8; the rest of the crate denies it. The minimum supported Rust version is 1.98.
+- A parsed message is read-only and is read through `Copy` views (`MessageRef`, `MessagePart`, `Headers`, `Header`, `HeaderValue`, `AddressList`, `ContentType`, `Received` and others) that borrow the message, so a value can no longer outlive the `Message` it came from. `Message` is still `Send`, `Sync`, `Clone` and `Default`; `Message::default()` is an empty message with one root part (id 0, no header field, empty body), so `root_part()`, `parts()` and `messages()` agree.
+- The header getters return views by value: `from()`, `to()`, `cc()`, `bcc()`, `reply_to()`, `sender()`, the `resent_*()` address getters and the `list_*()` getters return `Option`; `date()` and `resent_date()` return `Option`; `comments()` and `mime_version()` return `Option<&str>`; `in_reply_to()`, `references()`, `keywords()`, `resent_message_id()` and `return_path()` return `Option`; `received()` returns `Option`.
+- `text_bodies()` and `html_bodies()` yield the text of the parts of the text and HTML bodies (#73), converting HTML to text and text to HTML and skipping parts that are not text; 0.11 yielded the parts, which are now `text_body()` and `html_body()`. This change is silent where the item is only measured: `message.text_bodies().map(|body| body.len())` still compiles and now measures text.
+- Part identifiers are global: parts are numbered in document order across the root message and every nested message, and `Message::part()` takes such an id. A nested message is a `MessageRef` (`PartKind::Message`, `MessagePart::nested()`), no longer a `Message` inside the part. A base64 or quoted-printable encoded `message/rfc822` part is decoded and parsed during the parse; the offsets of its parts refer to its decoded body, as `MessageRef::source()` tells.
+- Address fields (#98) are an `AddressList` of mailboxes and groups in document order, whether or not they contain a group. 0.11 returned `Address::List` when there was no group and turned every run of mailboxes into an unnamed group as soon as there was one; that shape is now `AddressList::groups()`.
+- Message identifier fields, Keywords and Content-Language are always a `TextList`, even with one item; 0.11 switched between `Text` and `TextList`. `HeaderValue::as_text()` returns the last item of a list.
+- The body lists follow the RFC 8621 `parseStructure` algorithm exactly (#67). An image, audio or video part shown in both bodies is no longer also an attachment, and a named `text/html` alternative that follows a `text/plain` becomes an attachment while the `text/plain` is copied into `html_body`. Where the algorithm is silent: a text part of an alternative whose list an ancestor dropped goes to no list, a multipart that cannot be opened stays an attachment, a part without a usable Content-Type is `text/plain` (`message/rfc822` in a digest), and the name test uses the Content-Disposition `filename`, else the Content-Type `name`, an empty name counting as none. The `multipart/alternative` fix-up also runs when the alternative is not closed.
+- `PartKind::InlineBinary` and `MessagePart::is_inline()` follow the Content-Disposition (#70): `inline`, or no disposition on a child of `multipart/related` other than the first. 0.11 derived them from the RFC 8621 list rule, so images referenced by `cid:` in a `multipart/related` were `Binary`. The body lists are not affected.
+- Decoding no longer changes the part tree. 0.11 turned a part whose body failed to decode into a text part flagged `is_encoding_problem`; 1.0 keeps its kind, decodes it on a best-effort basis and reports the problems through `decoded_checked()` and `text_checked()`. `MessagePart::encoding()` is the declared Content-Transfer-Encoding, comments allowed (`base64 (comment)` is base64).
+- `is_encoding_problem` is split: `MessagePart::has_problems()` and `flags()` for damaged structure, `decoded_checked()` and `text_checked()` for decoding.
+- MIME delimiters (#156): a delimiter is `--boundary` at the start of a line followed by `--`, a space, a tab, CR, LF or the end of the input, checked against every open boundary, innermost first. A `--boundary` in the middle of a line ends a part only when the part has no valid delimiter at all, and the part is then flagged `FALLBACK_DELIMITER`. A multipart whose first delimiter is its close delimiter looks for a delimiter in the middle of a line of its preamble the same way (flagged `FALLBACK_DELIMITER`); a multipart closed before any part is flagged `MISSING_DELIMITER` and keeps its content in its preamble.
+- Malformed structure: a header block ends at a delimiter line (flagged `NO_BLANK_LINE`), an inner multipart that is never closed is closed by an outer delimiter, a part whose delimiter is missing is decoded and classified by its type, and every part ends by one rule (the end of the input, or before the line break that precedes the next delimiter), so a part never ends past its container: when a delimiter cuts a header block, or ends a part together with its container, the part ends where the container ends, and the last header field may end one line break past `offset_body()`.
+- RFC 2047 encoded words are decoded by encodify. No space is inserted between plain text and an adjacent encoded word, whitespace between two encoded words is dropped and whitespace between text and a word is kept as written. Adjacent words of one charset are joined before conversion, so a character split across two words decodes, and one-byte charset names are accepted.
+- Base64 bodies: bytes outside the alphabet are skipped and reported, a final unpadded quantum is decoded (0.11 dropped it) and a lone sextet before `=` no longer produces a byte. Quoted-printable bodies: `==` and other invalid escapes are kept as written (0.11 failed the whole part on `==`), trailing blanks at the end of the input are deleted (RFC 2045, section 6.7), and a soft line break right before a delimiter no longer deletes content.
+- Header blocks: a line without a colon at the end of the input is no longer a header field, the last field keeps its value when the input has no final line break, and a bare CR in unstructured text becomes a space.
+- Dates: the zone reader no longer consumes the next line after a `UT` or `Z` zone, and a one-digit zone such as `+5` means +05:00. Received fields: two-digit years follow the date parser (00 to 49 are 20xx), and `]` ends an address literal inside comments.
+- `MessageParser::header(name, form)` replaces the builder shorthands and changes the form of one field without dropping the default forms of the others. `unknown_headers()` also applies to the header names added in 1.0, unless they are registered with `header()`.
+- `HeaderName`: the names added in 1.0 are variants (`HeaderName::XMailer`), and an `Other` spelled like a known name, such as `Other("X-Mailer")`, equals, hashes and orders as that name; `MessageParser::header()`, `Headers::get()` and `Headers::all()` treat it as that name. `HeaderName::parse()` accepts every character RFC 5322 allows in a field name (printable US-ASCII except the colon; 0.11 accepted only letters, digits, `-` and `_`) and never allocates, and the `From` conversions keep any other string in `Other` with its spelling (0.11 returned `Other("")`, which matched no field). `Header::name()` returns a `HeaderName` (0.11: `&str`).
+- A header field that is present but blank and parsed as `Raw` or `Text` has the value `HeaderValue::Text("")`, so an empty `Subject:` gives `subject() == Some("")`, as RFC 8621 `asText` does; 0.11 returned no value. `HeaderValue::Empty` now means that the value does not parse in its form (an empty address list, date or Content-Type included) or that the field is parsed with `HeaderForm::Ignore`.
+- Header field names are matched strictly: a name with whitespace or a control character inside it (`Fr om`, `Sub\tject`) or starting with a colon (`:From`) is an unknown field kept with its spelling, where 0.11 read it as the known field, so mail-parser sees the same From and Subject as DKIM and DMARC verifiers. Space and tab between the name and the colon are still accepted (RFC 5322 obsolete syntax).
+- RFC 2231 parameters: the sections of a continued parameter are joined before they are converted, with the charset of the first section that declares one (section 0 in conforming input), and a language parameter (`name-language`) is reported once; 0.11 moved a repeated `'lang'` prefix into the value. A Content-Type or Content-Disposition field keeps at most 1,000 parameters.
+- `MessageParser::parse_headers()` records the real body offset; 0.11 reported the end of the input.
+- `MessageParser::parse()` returns `None` for input with no header field and no blank line, where 0.11 returned a message without headers and with an empty body, dropping the text. It also returns `None` for empty input and for input of 4 GiB or more.
+- `preview_text()`, `preview_html()`, `truncate_text()` and `truncate_html()` take `&str`, remove carriage returns themselves and borrow when they can; `body_preview()` decodes only the beginning of the body.
+- `text_to_html()` also escapes `&` and `>`.
+- `Charset::from_label()` maps the UTF-8 labels to `Charset::Utf8`; `charset_decoder()`, kept for compatibility, still returns `None` for them.
+- With the `serde` feature, a `Message` serializes to a new JSON shape (messages and parts in flat lists, with roles, flags and decoding problems) and implements `Serialize` only.
+- `mailbox::mbox::MessageIterator` finds separator lines with `memchr` and copies message contents in bulk. After an I/O error inside a line, the partial line is kept and reading continues on the next call.
+
+### Removed
+- The `rkyv` and `base64_slice` features.
+- The public fields and struct literals of `Message`, `MessagePart`, `Header`, `ContentType`, `Addr`, `Group` and `Attribute`, the methods that changed them (`Message::remove_header()`, `ContentType::remove_attribute()`), and `into_owned()` on parts and values.
+- `PartType` (replaced by `PartKind` and the decoding methods), `Addr` (replaced by `Mailbox`), `Attribute`, the `Address::List` and `Address::Group` shapes, `MessagePartId` (now `PartId`), the `GetHeader` and `MimeHeaders` traits (their methods are inherent), `MessageStream`, and the `core` and `parsers` modules.
+- `HeaderValue::unwrap_*()`, `into_*()`, `into_owned()` and `len()`; `HeaderForm::GroupedAddresses` and `HeaderForm::URLs` (use `HeaderForm::Addresses`); `HeaderName::len()`, `is_empty()` and `into_string()`.
+- The base64, quoted-printable and hex helpers: `base64_decode()`, `base64_decode_slice()`, `base64_decode_stream()`, `quoted_printable_decode()`, `quoted_printable_decode_char()`, `decode_hex()`, `HEX_MAP` and `BASE64_MAP`, with the `decoders::base64`, `decoders::quoted_printable`, `decoders::hex` and `decoders::encoded_word` modules; use encodify directly (`encodify::base64`, `qp`, `hex` and `rfc2047`). The `decoders::charsets::{map, multi_byte, single_byte, utf}` modules are replaced by `Charset`.
+- `MessagePart::is_text_html()`, `is_binary()` and `is_empty()`.
+- `PartialEq` for `Message` and `MessagePart`, and `Deserialize` for `Message`.
+- `trim_trailing_fwd()`, an internal step of `thread_name()`.
+
+### Fixed
+- MIME boundaries were matched anywhere in a line, which silently truncated body parts (#156).
+- Inline images in `multipart/related` were reported as `Binary` (#70).
+- `attachments` included inline media shown in both body lists, against RFC 8621 (#67).
+- `resent_cc()` returned the Resent-To field.
+- Registering one header parser disabled the default parsers of every other field.
+- An RFC 2231 value with a third apostrophe (`filename*=utf-8''O'Brien.txt`) was split at it.
+- The comment of an empty address group was attached to the next group.
+- `add_html_token()` panicked on invalid UTF-8.
+- `FolderIterator::next()` panicked when called after the end of the folders.
+- A multipart whose first delimiter line carried text after the boundary (`--b5Content-Type: ...`) made 0.11 panic in debug builds ("Invalid part ID, could not find multipart"); 1.0 keeps the content as a part.
+- RFC 2231 parameter sections were converted one by one, so a character split across two sections, or any section after the first in a charset other than UTF-8, became U+FFFD (`name*0*=utf-8''%E2%98; name*1*=%95.txt` now gives `☕.txt`).
+- RFC 2231 continuations took quadratic time in the number of sections or parameters of a field.
+- UTF-7 dropped the character that ends a base64 run (`+AKM.` gave `£` instead of `£.`) and did not decode `+-` to `+` (RFC 2152).
+- A UTF-16 text with an odd number of bytes lost its last byte silently; it now ends with U+FFFD, as documented.
+- `DateTime::to_timezone()` overflowed (a panic in debug builds) for offsets near `i64::MIN` or `i64::MAX`; it saturates.
+
+### Migrating from 0.11
+
+| 0.11 | 1.0 |
+|---|---|
+| `MessageParser::new().with_mime_headers()`, `with_date_headers()`, `with_address_headers()`, `with_message_ids()`, `with_minimal_headers()` | `MessageParser::new()`: the default forms parse these fields |
+| `header_text(name)`, `header_date(name)`, `header_address(name)`, `header_id(name)`, `header_comma_separated(name)`, `header_content_type(name)`, `header_received(name)`, `header_raw(name)`, `ignore_header(name)` | `header(name, form)` with `HeaderForm::Text`, `Date`, `Addresses`, `MessageIds`, `CommaList`, `ContentType`, `Received`, `Raw` or `Ignore` |
+| `without_header(name)` | `header(name, HeaderForm::Raw)` |
+| `default_header_text()`, `default_header_raw()`, `default_header_ignore()` | `unknown_headers(HeaderForm::Text)`, `Raw` or `Ignore` |
+| `MessageStream::new(value).parse_address()` and the other `parse_*()` | `HeaderForm::Addresses.parse(value).value()` and the other forms |
+| `message.header_as(name, form)` | `header.parse_as(form)` for each field of `message.headers().all(name)` |
+| `message.parts`, `message.parts[i]` | `message.parts()`, `message.part(id)` (ids are global across nested messages) |
+| `message.text_body`, `html_body`, `attachments` (lists of ids) | `message.text_body()`, `html_body()`, `attachments()` (iterators of `MessagePart`; `part.id()` gives the id) |
+| `message.text_part(i)`, `html_part(i)`, `attachment(i)` | `message.text_body().nth(i)`, `html_body().nth(i)`, `attachments().nth(i)` |
+| `message.text_body_count()`, `html_body_count()`, `attachment_count()` | `message.text_body().len()`, `html_body().len()`, `attachments().len()` |
+| `message.text_bodies()`, `html_bodies()` (parts) | `message.text_body()`, `html_body()`; `text_bodies()` and `html_bodies()` now yield text |
+| `message.raw_message`, `raw_message()` | `message.raw()` (the input) or `message.root().raw()` (the range of the root message) |
+| `message.header(name)` | `message.headers().value(name)` |
+| `message.header_raw(name)` | `raw_value()` (bytes) of `message.headers().get(name)` |
+| `message.header_values(name)` | `value()` of each field of `message.headers().all(name)` |
+| `message.headers()` (a slice), `headers_raw()` | `message.headers()` (a `Headers` view, iterated with `for header in message.headers()` or `iter()`); `raw_name()` and `raw_value()` of each field |
+| `message.remove_header(name)` | No replacement: messages are read-only |
+| `message.is_empty()` | `parse()` returns `None` for such input; `headers().has_known()` |
+| `from()`, `to()`, `cc()` and the other address getters (`Option<&Address>`) | `Option` |
+| `date()` (`Option<&DateTime>`), `resent_date()` (`&HeaderValue`) | `Option` |
+| `in_reply_to()`, `references()`, `keywords()`, `resent_message_id()`, `return_path()` (`&HeaderValue`) | `Option` |
+| `list_archive()` to `list_unsubscribe()` (`&HeaderValue`) | `Option` |
+| `comments()`, `mime_version()` (`&HeaderValue`) | `Option<&str>` |
+| `received()` (`Option<&Received>`) | `Option` |
+| `received_all()` | `all_received()`, like `all_to()`, `all_cc()` and `all_bcc()` |
+| `part.body` (`PartType`) | `part.kind()` (`PartKind`), with `text()`, `decoded()`, `nested()` and `children()` for the content |
+| `part.contents()` | `part.decoded()` |
+| `part.text_contents()` | `part.text()` |
+| `part.message()` (the nested message) | `part.nested()`; `part.message()` now returns the message the part belongs to |
+| `part.sub_parts()` | `part.children()` |
+| `part.len()` | `part.decoded_len()` |
+| `part.is_text_html()`, `part.is_binary()`, `part.is_empty()` | a match on `part.kind()`; `part.decoded_len() == 0` |
+| `part.is_encoding_problem` | `part.has_problems()` and `part.flags()`; `decoded_checked()` and `text_checked()` |
+| `part.encoding`, `part.headers` | `part.encoding()`, `part.headers()` |
+| `part.offset_header`, `offset_body`, `offset_end`, `raw_header_offset()`, `raw_body_offset()`, `raw_end_offset()` | `part.offset_header()`, `offset_body()`, `offset_end()` |
+| `part.raw_len()` | `part.raw().len()` |
+| `MimeHeaders` methods (`content_type()`, `content_id()`, `attachment_name()`, ...) | Inherent methods of `MessagePart` and `MessageRef`; `content_language()` returns `Option` |
+| `PartType::Message(message)` | `PartKind::Message(message)`, a `MessageRef` |
+| `header.name` (a `HeaderName`), `header.name()` (a `&str`) | `header.name()` (a `HeaderName`), `header.raw_name()` (as written) |
+| `header.value`, `header.offset_*` | `header.value()`, `header.offset_field()`, `offset_start()`, `offset_end()` (same meaning) |
+| `GetHeader::header()`, `header_value()` | `Headers::get()`, `Headers::value()` |
+| `HeaderValue::Text(Cow)` | `HeaderValue::Text(&str)` |
+| `HeaderValue::TextList(Vec>)` | `HeaderValue::TextList(TextList)`, also for a single item |
+| `HeaderValue::Address(Address::List(..))`, `HeaderValue::Address(Address::Group(..))` | `HeaderValue::Address(AddressList)` with `iter()`, `mailboxes()` and `groups()` |
+| `HeaderValue::Received(Box)` | `HeaderValue::Received(Received)`; hosts are returned by value |
+| `value.unwrap_text()`, `into_text()` and the other `unwrap_*()` and `into_*()` | `as_text()`, `as_text_list()`, `as_address()`, `as_datetime()`, `as_content_type()`, `as_received()` |
+| `Address::first()`, `last()`, `contains()`, `iter()` | `AddressList::first()`, `last()`, `contains()`, `mailboxes()` |
+| `Address::as_list()`, `as_group()`, `into_list()`, `into_group()` | `AddressList::mailboxes()`, `AddressList::groups()` |
+| `Addr` (`name`, `address`) | `Mailbox` (`name()`, `address()`) |
+| `Group` (`name`, `addresses`) | `Group` (`name()`, `mailboxes()`) |
+| `ContentType` (`c_type`, `c_subtype`, `attributes`) | `ContentType` (`ctype()`, `subtype()`, `attribute()`, `attributes()` yielding name and value) |
+| `HeaderName::Other("X-Mailer")` and the other names added in 1.0 | `HeaderName::XMailer`; an `Other` with the same spelling still finds and configures the field, but `header.name()` returns the variant |
+| `HeaderValue::Empty` for a blank Subject or other text field (`subject() == None`) | `HeaderValue::Text("")` (`subject() == Some("")`) |
+| `HeaderName::from("X.Spam")` gave `Other("")` | `Other("X.Spam")`, which finds the field |
+| `HeaderName::into_string()`, `len()` | `String::from(name)`, `name.as_str().len()` |
+| `MessagePartId` | `PartId` |
+| `decoders::base64::base64_decode()`, `base64_decode_slice()`, `base64_decode_stream()`, `BASE64_MAP` | `encodify::base64` |
+| `decoders::quoted_printable::quoted_printable_decode()`, `quoted_printable_decode_char()`, `HEX_MAP` | `encodify::qp` |
+| `decoders::hex::decode_hex()` | `encodify::hex` |
+| `decoders::charsets::map::charset_decoder()` | `Charset::from_label()` and `Charset::decode()`; `decoders::charsets::charset_decoder()` is kept |
+| `parsers::preview::preview_text()` and the other preview functions (taking `Cow`) | `preview_text()` and the others at the crate root, taking `&str` |
+| `parsers::fields::thread::thread_name()` | `thread_name()` |
+| `parsers::fields::address::parse_address_local_part()` and the other address helpers | `parse_address_local_part()` and the others at the crate root |
+| `rkyv` feature | No replacement |
+| `base64_slice` feature | encodify |
+
+## [0.11.9] - 2026-09-09
+
+### Added
- Added `base64_decode_slice` behind the new `base64_slice` feature, which adds a `memchr` dependency.
-mail-parser 0.11.8
-================================
-- Fix: `HeaderName` breaks rkyv serialization from <= 0.11.6.
+## [0.11.8] - 2026-08-22
-mail-parser 0.11.7
-================================
+### Fixed
+- `HeaderName` breaks rkyv serialization from <= 0.11.6.
+
+## [0.11.7] - 2026-08-20
+
+### Added
- Added more IANA headers.
-- Fix: `DateTime::to_timezone` corrupting non-whole-hour offsets by storing leftover seconds in `tz_minute` (#158)
-mail-parser 0.11.6
-================================
-- Fix: Missing whitespace between a quoted name and a following encoded word (#150)
-- Fix: `panic` when a `Received` header ends with a folded line (#155)
-- Fix: `Received` header tokens losing their last character at the end of the input, retaining folding characters, and failing to parse a clause folded before its value (#155)
-- Fix: Multi-word display names followed by a comment no longer produce a fabricated address (#153)
+### Fixed
+- `DateTime::to_timezone` corrupting non-whole-hour offsets by storing leftover seconds in `tz_minute` (#158)
-mail-parser 0.11.5
-================================
-- Fix: Address names containing LF are not parsed correctly (#149)
-- Fix: Decode the `iso-8859-1` label as `windows-1252` per the WHATWG Encoding Standard (#131)
-- Fix: `panic` with messages containing corrupted eml attachments (#120).
+## [0.11.6] - 2026-08-10
+
+### Fixed
+- Missing whitespace between a quoted name and a following encoded word (#150)
+- `panic` when a `Received` header ends with a folded line (#155)
+- `Received` header tokens losing their last character at the end of the input, retaining folding characters, and failing to parse a clause folded before its value (#155)
+- Multi-word display names followed by a comment no longer produce a fabricated address (#153)
+
+## [0.11.5] - 2026-07-08
+
+### Added
- Recognize additional charset labels supported by `encoding_rs` (#123)
- Added `Dkim2Signature` and `MessageInstance` to support DKIM2 headers.
-mail-parser 0.11.4
-================================
+### Fixed
+- Address names containing LF are not parsed correctly (#149)
+- Decode the `iso-8859-1` label as `windows-1252` per the WHATWG Encoding Standard (#131)
+- `panic` with messages containing corrupted eml attachments (#120).
+
+## [0.11.4] - 2026-06-21
+
+### Added
- Add `Message::received_all()` to iterate over all Received header fields (#146)
+
+### Changed
- Reject dates with invalid month names.
-- `parse_date()` doesn't handle UTC+12 and greater (#148)
- Leniently decode quoted-printable bodies with invalid `=` escapes (#144)
-mail-parser 0.11.3
-================================
+### Fixed
+- `parse_date()` doesn't handle UTC+12 and greater (#148)
+
+## [0.11.3] - 2026-05-02
+
+### Fixed
- Fix panic with messages containing corrupted attachments (#145)
-mail-parser 0.11.2
-================================
+## [0.11.2] - 2026-02-14
+
+### Fixed
- Do not return invalid mime parts when parsing broken nested messages.
- Fix broken receive header date parsing when tab is used in long header syntax (#130)
-mail-parser 0.11.1
-================================
+## [0.11.1] - 2025-08-18
+
+### Fixed
- Fix `DateTime::from_timestamp` to handle negative timestamps correctly.
-mail-parser 0.11.0
-================================
+## [0.11.0] - 2025-05-11
+
+### Added
- `rkyv` zero-copy deserialization support.
+
+### Changed
- Changed `usize` to `u32` types.
- Renamed `serde_support` feature to `serde`.
-- Fix: Parsing of headers without LFs (#102)
-mail-parser 0.10.2
-================================
+### Fixed
+- Parsing of headers without LFs (#102)
+
+## [0.10.2] - 2025-01-28
+
+### Fixed
- Fixed `HeaderName` enum order to avoid breaking bincode serialization.
-mail-parser 0.10.1
-================================
+## [0.10.1] - 2025-01-26
+
+### Fixed
- Fixed `HeaderName::parse` function.
-mail-parser 0.10.0
-================================
+## [0.10.0] - 2025-01-26
+
+### Added
+- Added `DkimSignature`, `ArcAuthenticationResults`, `ArcMessageSignature` and `ArcSeal` headers.
+
+### Changed
- Perfect hashing using `hashify` crate rather than static `gperf` generated code.
-- Added `DkimSignature`, `ArcAuthenticationResults`, `ArcMessageSignature` and `ArcSeal` headers.
- `HeaderName` is non-exhaustive.
- Parse obsolete timezones (#95).
-- Fix: Folding ws between "Content-Type:" and "plain/text" leads to empty header (#96).
-- Fix: Multiline quoted continuations (closes #92).
-- Fix: Deserialize (#93).
- Retain mbox IO errors (#91).
- Hide concrete type behind impl type (#94).
+
+### Removed
- Removed `ludicrous` feature, the Rust compiler is smart enough to optimize array lookups.
-mail-parser 0.9.4
-================================
+### Fixed
+- Folding ws between "Content-Type:" and "plain/text" leads to empty header (#96).
+- Multiline quoted continuations (closes #92).
+- Deserialize (#93).
+
+## [0.9.4] - 2024-09-04
+
+### Changed
- Flexible parsing of charset names (#85).
-mail-parser 0.9.3
-================================
+## [0.9.3] - 2024-03-28
+
+### Fixed
- Fixed parsing of address names containing @ (#80)
-mail-parser 0.9.2
-================================
+## [0.9.2] - 2023-11-27
+
+### Fixed
- Fixed `quoted_printable_decode` external function (not used by mail-parser directly).
- Fix `Received` header serialization for bincode compatibility.
-mail-parser 0.9.1
-================================
-- Fixed panic when Content-Disposition is empty (#63)
-- Removed `content_type()` and `address()` functions that could `panic!`. Use `as_content_type()` and `as_address()` instead.
+## [0.9.1] - 2023-09-22
+
+### Changed
- Updated Rust edition to 2021.
-mail-parser 0.9.0
-================================
+### Removed
+- Removed `content_type()` and `address()` functions that could `panic!`. Use `as_content_type()` and `as_address()` instead.
+
+### Fixed
+- Fixed panic when Content-Disposition is empty (#63)
+
+## [0.9.0] - 2023-09-05
+
This version introduces multiple breaking changes. Please read the following notes carefully.
-- Parsing is now done using `MessageParser`, which allows to customize the parsing process.
+### Added
- Added parser for `Received` headers.
- Added `MessageParser::parse_headers` function to parse only the headers of a message.
-- Removed `RfcHeader` enum, now all headers are represented using `HeaderName`.
+
+### Changed
+- Parsing is now done using `MessageParser`, which allows to customize the parsing process.
- All address types are now stored in the `HeaderValue::Address` variant using the `Address` enum.
- Renamed the `as_` prefix to `to_` in some functions.
-mail-parser 0.8.2
-================================
-- Fix: Parsing address name with \ characters (#41)
-- Fix: Missing space when folded header begins with RFC2047 word (#43)
+### Removed
+- Removed `RfcHeader` enum, now all headers are represented using `HeaderName`.
-mail-parser 0.8.1
-================================
+## [0.8.2] - 2023-02-22
+
+### Fixed
+- Parsing address name with \ characters (#41)
+- Missing space when folded header begins with RFC2047 word (#43)
+
+## [0.8.1] - 2023-02-09
+
+### Added
- Added `raw_message()` function.
-mail-parser 0.8.0
-================================
+## [0.8.0] - 2022-12-01
+
+### Changed
- Removed get_() prefixes (#31).
- Maildir import: Use modified time instead of created time (#32)
-mail-parser 0.7.0
-================================
-- Base64/QuotedPrintable decoding optimizations.
+## [0.7.0] - 2022-10-21
+
+### Added
- Automatic parsing of base64/qp encoded nested messages.
-- Refactoring or ``MessageStream`` to use iterators more efficiently.
- Added "ludicrous mode" Cargo option to use some unsafe code for additional performance.
+
+### Changed
+- Base64/QuotedPrintable decoding optimizations.
+- Refactoring or ``MessageStream`` to use iterators more efficiently.
+
+### Fixed
- Fixed support for empty messages.
- Fixed raw offsets of multipart/* parts to include MIME epilogue.
- Fixed values of non-RFC headers.
-mail-parser 0.6.1
-================================
+## [0.6.1] - 2022-09-09
+
+### Added
- Support for malformed unstructured fields containing encoded words (#29).
- Add support for gb2312 charsets (#30).
-mail-parser 0.6.0
-================================
+## [0.6.0] - 2022-08-21
+
+### Added
- Maildir parsing support.
-- Headers and attributes are now stored in a `Vec` instead of a `HashMap` for a tiny performance enhancement.
- Support for Content-Type attributes spanning multiple lines.
-- Support for malformed Thunderbird messages (#27).
+- Support for malformed Thunderbird messages (#27).
+
+### Changed
+- Headers and attributes are now stored in a `Vec` instead of a `HashMap` for a tiny performance enhancement.
+
+### Fixed
- Fixed raw offset range for body parts.
-mail-parser 0.5.0
-================================
+## [0.5.0] - 2022-07-15
+
+### Added
+- Added raw offsets to MIME parts.
+
+### Changed
- `Message` headers are now stored as a `MessagePart` with index 0.
- Improved `MessagePart` API.
- Nested base64/quoted-printable encoded message/rfc822 parts are automatically parsed when calling `get_message`.
- Better handling of malformed MIME messages.
-- Added raw offsets to MIME parts.
-mail-parser 0.4.8
-================================
+## [0.4.8] - 2022-06-06
+
+### Fixed
- get_bytes_to_boundary fix (#21)
-mail-parser 0.4.7
-================================
+## [0.4.7] - 2022-06-03
+
+### Added
- Retrieving message headers in order (#19)
- Added `get_raw_headers` and `get_header` methods.
- Added `get_return_address` method to obtain the return address from the Return-Path or From headers.
- Support for malformed Return-Path headers.
- Support for ks_c_5601 charsets (#20)
-mail-parser 0.4.6
-================================
+## [0.4.6]
+
+### Fixed
- DateTime is_valid() fix (#15)
-
-mail-parser 0.4.5
-================================
+
+## [0.4.5] - 2022-03-14
+
+### Added
- DateTime to UNIX timestamp conversion.
- Ord, PartialOrd support for DateTime (#13).
+
+### Fixed
- Fixed Message::parse() panic on duplicate Content-Type headers (#14).
-mail-parser 0.4.4
-================================
+## [0.4.4] - 2022-01-24
+
+### Added
- Support for multi-line headers.
- Text and HTML message body preview.
+
+### Changed
- Improved support for raw headers.
-mail-parser 0.4.3
-================================
+## [0.4.3] - 2021-12-31
+
+### Added
- Mbox file parsing support (issue #11) conforming to the [QMail specification](http://qmail.org/qmail-manual-html/man5/mbox.html).
- Support for bincode serialize/deserialize.
-mail-parser 0.4.2
-================================
+## [0.4.2] - 2021-12-22
+
+### Added
- Added `Message::get_thread_name()` to obtain the base subject of a message as defined in [RFC 5957 - Internet Message Access Protocol - SORT and THREAD Extensions (Section 2.1)](https://datatracker.ietf.org/doc/html/rfc5256#section-2.1).
- Added `MimeHeader::get_attachment_name` for simplified access to a MIME attachment file name.
-mail-parser 0.4.1
-================================
-- Lazy parsing of nested e-mail messages.
+## [0.4.1] - 2021-12-16
+
+### Added
- Support for base64/quoted-printable nested messages.
-mail-parser 0.4.0
-================================
+### Changed
+- Lazy parsing of nested e-mail messages.
+
+## [0.4.0] - 2021-12-16
+
+### Changed
- Lazy conversion to/from HTML an plain text parts.
- Improved API.
- Parts are now generics.
-mail-parser 0.3.1
-================================
+## [0.3.1] - 2021-12-15
+
+### Added
- Support for non-standard headers.
+
+### Changed
- Raw message offsets are stored in the message object.
- Message body structure is now stored in the message object.
-mail-parser 0.3
-================================
-- Improved API, now `Message::parse` returns `Option` to indicate when parsing was successful.
-- Headers are now stored internally in a `HashMap` instead of `struct` fields.
+## [0.3.0] - 2021-11-08
+
+### Added
- Added support for new RFCs:
- [RFC 2557 - MIME Encapsulation of Aggregate Documents, such as HTML (MHTML)](https://datatracker.ietf.org/doc/html/rfc2557)
- [RFC 2392 - Content-ID and Message-ID Uniform Resource Locators](https://datatracker.ietf.org/doc/html/rfc2392)
- [RFC 3282 - Content Language Headers](https://datatracker.ietf.org/doc/html/rfc3282)
- [RFC 3339 - Date and Time on the Internet: Timestamps](https://datatracker.ietf.org/doc/html/rfc3339)
-mail-parser 0.2.1
-================================
+### Changed
+- Improved API, now `Message::parse` returns `Option` to indicate when parsing was successful.
+- Headers are now stored internally in a `HashMap` instead of `struct` fields.
+
+## [0.2.2] - 2021-11-04
+
+### Changed
+- Improved decoder results.
+- Dependency requirements for `encoding_rs`, `serde` and `serde_bytes` use caret ranges (`0.8`, `1.0` and `0.11`) instead of `>=0.8.28`, `>=1.0.117` and `>=0.11.5`.
+
+## [0.2.1] - 2021-11-03
+
+### Changed
- Performance enhacements, now *mail-parser* is almost as fast as the `unsafe` 0.1 version.
-mail-parser 0.2
-================================
-- Re-factoring to use **100% safe** Rust after a [discussion on Reddit](https://www.reddit.com/r/rust/comments/qkc5rk/fast_and_robust_email_parsing_library_for_rust/).
+## [0.2.0] - 2021-11-03
+
+### Added
- Added `Message::is_empty`.
-mail-parser 0.1.1
-================================
+### Changed
+- Re-factoring to use **100% safe** Rust after a [discussion on Reddit](https://www.reddit.com/r/rust/comments/qkc5rk/fast_and_robust_email_parsing_library_for_rust/).
+
+## [0.1.1] - 2021-11-02
+
+### Fixed
- Bug-fixing after **fuzzing** the library.
-mail-parser 0.1
-================================
+## [0.1.0] - 2021-11-01
+
+### Added
- Initial release with plenty of `unsafe` code to speed things up.
-
-
-
-
-
-
diff --git a/Cargo.toml b/Cargo.toml
index 3fc4492..2156996 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,8 +1,9 @@
[package]
name = "mail-parser"
description = "Fast and robust e-mail parsing library for Rust"
-version = "0.11.9"
+version = "1.0.0"
edition = "2024"
+rust-version = "1.98"
authors = [ "Stalwart Labs "]
license = "Apache-2.0 OR MIT"
repository = "https://github.com/stalwartlabs/mail-parser"
@@ -10,31 +11,42 @@ homepage = "https://github.com/stalwartlabs/mail-parser"
keywords = ["email", "mail", "parser", "parse", "mime"]
categories = ["email", "parser-implementations"]
readme = "README.md"
-resolver = "2"
[dependencies]
-hashify = { version = "0.3" }
-memchr = { version = "2.7", optional = true }
+hashify = "0.3"
+memchr = "2.8"
+simdutf8 = "0.1"
+encodify = { path = "../encodify" }
encoding_rs = { version = "0.8", optional = true }
serde = { version = "1.0", features = ["derive"], optional = true }
-rkyv = { version = "0.8", optional = true }
[dev-dependencies]
-mail-parser = { path = ".", features = ["serde", "full_encoding"] }
-serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
-bincode = "1.3.3"
chrono = "0.4"
+criterion = { version = "0.8", default-features = false, features = ["cargo_bench_support"] }
[features]
default = []
-full_encoding = ["encoding_rs"]
+full_encoding = ["dep:encoding_rs"]
serde = ["dep:serde"]
-rkyv = ["dep:rkyv"]
-base64_slice = ["dep:memchr"]
+
+[[bench]]
+name = "kernels"
+harness = false
+
+[[bench]]
+name = "resolve"
+harness = false
+
+[lints.rust]
+rust_2018_idioms = { level = "deny", priority = -1 }
+unsafe_code = "deny"
+unsafe_op_in_unsafe_fn = "deny"
+unexpected_cfgs = { level = "warn", check-cfg = ["cfg(mail_parser_checked_str)"] }
+
+[lints.clippy]
+undocumented_unsafe_blocks = "deny"
+unwrap_used = "deny"
[profile.bench]
debug = true
-
-[lib]
-doctest = false
diff --git a/README.md b/README.md
index 8a7d56a..500da7f 100644
--- a/README.md
+++ b/README.md
@@ -3,38 +3,40 @@
[](https://crates.io/crates/mail-parser)
[](https://github.com/stalwartlabs/mail-parser/actions/workflows/rust.yml)
[](https://docs.rs/mail-parser)
+[](https://crates.io/crates/mail-parser)
[](http://www.apache.org/licenses/LICENSE-2.0)
-_mail-parser_ is an **e-mail parsing library** written in Rust that fully conforms to the Internet Message Format standard (_RFC 5322_), the
-Multipurpose Internet Mail Extensions (MIME; _RFC 2045 - 2049_) as well as many other [internet messaging RFCs](#conformed-rfcs).
+_mail-parser_ is an **e-mail parsing library** written in Rust that fully conforms to the Internet Message Format standard (_RFC 5322_), the Multipurpose Internet Mail Extensions (MIME; _RFC 2045 - 2049_) as well as many other [internet messaging RFCs](#conformed-rfcs).
-It also supports decoding messages in [41 different character sets](#supported-character-sets) including obsolete formats such as UTF-7.
-All Unicode (UTF-*) and single-byte character sets are handled internally by the library while support for legacy multi-byte encodings of Chinese
-and Japanese languages such as BIG5 or ISO-2022-JP is provided by the optional dependency [encoding_rs](https://crates.io/crates/encoding_rs).
+It also supports decoding messages in [41 different character sets](#supported-character-sets) including obsolete formats such as UTF-7. All Unicode (UTF-*) and single-byte character sets are handled internally by the library while support for legacy multi-byte encodings of Chinese and Japanese languages such as BIG5 or ISO-2022-JP is provided by the optional dependency [encoding_rs](https://crates.io/crates/encoding_rs).
-In general, this library abides by the Postel's law or [Robustness Principle](https://en.wikipedia.org/wiki/Robustness_principle) which
-states that an implementation must be conservative in its sending behavior and liberal in its receiving behavior. This means that
-_mail-parser_ will make a best effort to parse non-conformant e-mail messages as long as these do not deviate too much from the standard.
+In general, this library abides by the Postel's law or [Robustness Principle](https://en.wikipedia.org/wiki/Robustness_principle) which states that an implementation must be conservative in its sending behavior and liberal in its receiving behavior. This means that _mail-parser_ will make a best effort to parse non-conformant e-mail messages as long as these do not deviate too much from the standard.
-Unlike other e-mail parsing libraries that return nested representations of the different MIME parts in a message, this library
-conforms to [RFC 8621, Section 4.1.4](https://datatracker.ietf.org/doc/html/rfc8621#section-4.1.4) and provides a more human-friendly
-representation of the message contents consisting of just text body parts, html body parts and attachments. Additionally, conversion to/from
-HTML and plain text inline body parts is done automatically when the _alternative_ version is missing.
+Besides the MIME tree, every message comes with the three body lists of [RFC 8621, Section 4.1.4](https://datatracker.ietf.org/doc/html/rfc8621#section-4.1.4): the text body, the HTML body and the attachments. HTML is converted to plain text, and plain text to HTML, when a part has no alternative in the other format.
-Performance and memory safety were two important factors while designing _mail-parser_:
+## Features
-- **Zero-copy**: Practically all strings returned by this library are `Cow` references to the input raw message.
-- **High performance Base64 decoding** based on Chromium's decoder ([the fastest non-SIMD decoder](https://github.com/lemire/fastbase64)).
-- **Fast parsing** of message header fields, character set names and HTML entities using [perfect hashing](https://en.wikipedia.org/wiki/Perfect_hash_function).
-- Written in **100% safe** Rust with no external dependencies.
-- Every function in the library has been [fuzzed](#testing-fuzzing--benchmarking) and thoroughly [tested with MIRI](#testing-fuzzing--benchmarking).
+- **Fast parsing**:
+ - Boundaries and header fields are found by SIMD kernels (NEON on aarch64, AVX2 and SSE2 on x86-64, `memchr` on every other target).
+ - Base64 and quoted-printable are decoded by the SIMD codecs of [encodify](https://github.com/stalwartlabs/encodify)
+ - UTF-8 is validated by [simdutf8](https://crates.io/crates/simdutf8)
+ - Header names, charset labels and HTML entities are looked up with perfect hashing through [hashify](https://crates.io/crates/hashify).
+- **Lazy decoding**: Nothing is transfer-decoded or converted from its character set during the parse; a message whose attachments are never read never pays for decoding them.
+- **Zero-copy**: Practically all strings returned by this library are references to the input raw message.
- **Battle-tested** with millions of real-world e-mail messages dating from 1995 until today.
+- Every function in the library has been [fuzzed](#testing-fuzzing--benchmarking) and thoroughly [tested with MIRI](#testing-fuzzing--benchmarking).
- Used in production environments worldwide by [Stalwart Mail Server](https://github.com/stalwartlabs/mail-server).
-## Usage Example
+> Note: This library does not support building e-mail messages as this functionality is provided separately by the [`mail-builder`](https://crates.io/crates/mail-builder) crate.
+
+## Usage
+
+### Parse a message
```rust
- let input = br#"From: Art Vandelay (Vandelay Industries)
+use mail_parser::{Address, MessageParser, PartKind};
+
+let input = br#"From: Art Vandelay (Vandelay Industries)
To: "Colleagues": "James Smythe" ; Friends:
jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= ;
Date: Sat, 20 Nov 2021 14:22:01 -0800
@@ -75,126 +77,294 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
--festivus--
"#;
- let message = MessageParser::default().parse(input).unwrap();
+let message = MessageParser::default().parse(input).expect("a message");
- // Parses addresses (including comments), lists and groups
- assert_eq!(
- message.from().unwrap().first().unwrap(),
- &Addr::new(
- "Art Vandelay (Vandelay Industries)".into(),
- "art@vandelay.com"
- )
- );
+let sender = message.from().and_then(|from| from.first()).expect("a sender");
+assert_eq!(sender.name(), Some("Art Vandelay (Vandelay Industries)"));
+assert_eq!(sender.address(), Some("art@vandelay.com"));
- assert_eq!(
- message.to().unwrap().as_group().unwrap(),
- &[
- Group::new(
- "Colleagues",
- vec![Addr::new("James Smythe".into(), "james@vandelay.com")]
- ),
- Group::new(
- "Friends",
- vec![
- Addr::new(None, "jane@example.com"),
- Addr::new("John Smîth".into(), "john@example.com"),
- ]
- )
- ]
- );
+let to = message.to().expect("recipients");
+let addresses: Vec<_> = to.mailboxes().filter_map(|mailbox| mailbox.address()).collect();
+assert_eq!(addresses, ["james@vandelay.com", "jane@example.com", "john@example.com"]);
+let Some(Address::Group(friends)) = to.iter().nth(1) else {
+ panic!("the second item is a group");
+};
+assert_eq!(friends.name(), Some("Friends"));
+assert_eq!(friends.mailboxes().nth(1).and_then(|mailbox| mailbox.name()), Some("John Smîth"));
- assert_eq!(
- message.date().unwrap().to_rfc3339(),
- "2021-11-20T14:22:01-08:00"
- );
+assert_eq!(message.date().expect("a date").to_rfc3339(), "2021-11-20T14:22:01-08:00");
+assert_eq!(message.subject(), Some("Why not both importing AND exporting? ☺"));
- // RFC2047 support for encoded text in message readers
- assert_eq!(
- message.subject().unwrap(),
- "Why not both importing AND exporting? ☺"
- );
+assert_eq!(
+ message.body_html(0).as_deref(),
+ Some(concat!(
+ "
I was thinking about quitting the “exporting” to ",
+ "focus just on the “importing”,
but then I thought,",
+ " why not do both? ☺
"
+ ))
+);
+assert_eq!(
+ message.body_text(0).as_deref(),
+ Some(concat!(
+ "I was thinking about quitting the “exporting” to focus just on the",
+ " “importing”,\nbut then I thought, why not do both? ☺\n"
+ ))
+);
- // HTML and text body parts are returned conforming to RFC8621, Section 4.1.4
- assert_eq!(
- message.body_html(0).unwrap(),
- concat!(
- "
I was thinking about quitting the “exporting” to ",
- "focus just on the “importing”,
but then I thought,",
- " why not do both? ☺
"
- )
- );
+let nested = message
+ .attachments()
+ .find_map(|part| part.nested())
+ .expect("a nested message");
+assert_eq!(nested.subject(), Some("Exporting my book about coffee tables"));
+assert_eq!(nested.body_text(0).as_deref(), Some("ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!"));
+assert_eq!(
+ nested.body_html(0).as_deref(),
+ Some("ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!")
+);
- // HTML parts are converted to plain text (and viceversa) when missing
- assert_eq!(
- message.body_text(0).unwrap(),
- concat!(
- "I was thinking about quitting the “exporting” to focus just on the",
- " “importing”,\nbut then I thought, why not do both? ☺\n"
- )
- );
-
- // Supports nested messages as well as multipart/digest
- let nested_message = message
- .attachment(0)
- .unwrap()
- .message();
- .unwrap();
-
- assert_eq!(
- nested_message.subject().unwrap(),
- "Exporting my book about coffee tables"
- );
-
- // Handles UTF-* as well as many legacy encodings
- assert_eq!(
- nested_message.body_text(0).unwrap(),
- "ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!"
- );
- assert_eq!(
- nested_message.body_html(0).unwrap(),
- "ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!"
- );
-
- let nested_attachment = nested_message.attachment(0).unwrap();
-
- assert_eq!(nested_attachment.len(), 42);
-
- // Full RFC2231 support for continuations and character sets
- assert_eq!(
- nested_attachment.attachment_name().unwrap(),
- "Book about ☕ tables.gif"
- );
-
- // Integrates with Serde
- println!("{}", serde_json::to_string_pretty(&message).unwrap());
+let image = nested.attachments().next().expect("an attachment");
+assert_eq!(image.attachment_name(), Some("Book about ☕ tables.gif"));
+assert!(matches!(image.kind(), PartKind::Binary));
+assert_eq!(image.decoded_len(), 42);
```
-More examples available under the [examples](examples) directory. Please note that this library does not support building e-mail messages as this functionality is provided separately by the [`mail-builder`](https://crates.io/crates/mail-builder) crate.
+### Read header fields
+
+```rust
+use mail_parser::{HeaderName, HeaderValue, MessageParser};
+
+let raw = b"Received: from mx.example.com by mail.example.org; Sat, 20 Nov 2021 14:22:05 -0800\r\n\
+Message-ID: <1234@example.com>\r\n\
+X-Priority: 1\r\n\
+X-Custom: first\r\n\
+X-Custom: second\r\n\
+Subject: Status report\r\n\
+\r\n\
+Body\r\n";
+let message = MessageParser::new().parse(raw).expect("a message");
+let headers = message.headers();
+
+assert_eq!(message.message_id(), Some("1234@example.com"));
+assert_eq!(headers.get("x-custom").map(|header| header.raw_value()), Some(&b" second\r\n"[..]));
+assert_eq!(headers.all("X-Custom").count(), 2);
+assert!(headers.contains(HeaderName::XPriority));
+
+for header in headers {
+ match header.value() {
+ HeaderValue::Text(text) => println!("{}: {text}", header.raw_name()),
+ HeaderValue::Received(received) => println!("received by {:?}", received.by()),
+ other => println!("{}: {other:?}", header.raw_name()),
+ }
+}
+```
+
+### Decode bodies on demand
+
+```rust
+use mail_parser::{DecodeProblems, MessageParser};
+
+let raw = concat!(
+ "Content-Type: multipart/mixed; boundary=\"b\"\r\n",
+ "\r\n",
+ "--b\r\n",
+ "Content-Type: text/plain; charset=iso-8859-1\r\n",
+ "Content-Transfer-Encoding: quoted-printable\r\n",
+ "\r\n",
+ "Caf=E9 cr=E8me\r\n",
+ "--b\r\n",
+ "Content-Type: application/octet-stream\r\n",
+ "Content-Transfer-Encoding: base64\r\n",
+ "\r\n",
+ "AAEC*AwQF\r\n",
+ "--b--\r\n",
+);
+let message = MessageParser::new().parse(raw).expect("a message");
+
+let text = message.text_body().next().expect("a text part");
+assert_eq!(text.text().as_deref(), Some("Café crème"));
+assert_eq!(text.text_prefix(4).as_deref(), Some("Café"));
+
+let file = message.attachments().next().expect("an attachment");
+assert_eq!(file.decoded().as_ref(), b"\x00\x01\x02\x03\x04\x05");
+assert_eq!(file.decoded_len(), 6);
+let (_, problems) = file.decoded_checked();
+assert!(problems.contains(DecodeProblems::MALFORMED_TRANSFER_ENCODING));
+```
+
+### Walk the MIME structure
+
+```rust
+use mail_parser::{MessageParser, Source};
+
+let raw = concat!(
+ "Content-Type: multipart/mixed; boundary=\"outer\"\r\n",
+ "\r\n",
+ "--outer\r\n",
+ "Content-Type: multipart/alternative; boundary=\"inner\"\r\n",
+ "\r\n",
+ "--inner\r\n",
+ "Content-Type: text/plain\r\n",
+ "\r\n",
+ "Hello\r\n",
+ "--inner\r\n",
+ "Content-Type: text/html\r\n",
+ "\r\n",
+ "
"
+ );
+ let output = html_to_text(input);
+ assert!(!output.contains("Hidden"));
+ assert!(!output.contains(".x{}"));
+ assert!(output.contains("Hello"));
+ assert!(output.contains("World"));
+ }
+
+ #[test]
+ fn charset_meta_is_rewritten() {
+ for (html, expected) in [
+ (
+ "\u{2014}",
+ "\u{2014}",
+ ),
+ (
+ "\u{2014}",
+ "\u{2014}",
+ ),
+ (
+ "\u{2014}",
+ "\u{2014}",
+ ),
+ (
+ "\u{2014}",
+ "\u{2014}",
+ ),
+ ] {
+ assert_eq!(strip_charset_meta(html), expected);
+ }
+ for html in [
+ "x",
+ "",
+ "plain text",
+ ] {
+ assert!(matches!(strip_charset_meta(html), Cow::Borrowed(_)));
+ }
+ }
+}
diff --git a/src/decoders/html/text.rs b/src/decoders/html/text.rs
new file mode 100644
index 0000000..b1df415
--- /dev/null
+++ b/src/decoders/html/text.rs
@@ -0,0 +1,316 @@
+/*
+ * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC
+ *
+ * SPDX-License-Identifier: Apache-2.0 OR MIT
+ */
+
+use memchr::{memchr, memchr2};
+
+use super::decode_entity;
+
+const COMMENT_OPEN: &[u8] = b"--";
+const COMMENT_CLOSE_DASHES: usize = 2;
+const NAMED_TAG: usize = 1;
+
+static TEXT_DELIMITERS: [bool; 256] = delimiters(b"<&; \t\r\n");
+static TAG_DELIMITERS: [bool; 256] = delimiters(b"<>/ \t\r\n");
+
+const fn delimiters(bytes: &[u8]) -> [bool; 256] {
+ let mut table = [false; 256];
+ let mut index = 0;
+ while index < bytes.len() {
+ table[bytes[index] as usize] = true;
+ index += 1;
+ }
+ table
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Mode {
+ Complete,
+ Preview { limit: usize },
+}
+
+pub(super) fn html_to_text(input: &str) -> String {
+ let mut out = String::with_capacity(input.len());
+ convert(input, &mut out, Mode::Complete);
+ out
+}
+
+pub(crate) fn html_to_text_prefix(input: &str, limit: usize, out: &mut String) -> bool {
+ convert(input, out, Mode::Preview { limit })
+}
+
+fn convert(input: &str, out: &mut String, mode: Mode) -> bool {
+ let bytes = input.as_bytes();
+ let mut sink = Sink {
+ input,
+ bytes,
+ out,
+ mode,
+ pending_start: 0,
+ pending_end: 0,
+ };
+ let mut in_tag = false;
+ let mut in_head = false;
+ let mut in_style = false;
+ let mut in_script = false;
+ let mut in_template = false;
+ let mut is_token_start = true;
+ let mut is_after_space = false;
+ let mut is_tag_close = false;
+ let mut is_new_line = true;
+ let mut token_start = 0;
+ let mut token_end = 0;
+ let mut tag_token_pos = 0;
+ let mut pos = 0;
+
+ loop {
+ let hidden = in_head || in_style || in_script || in_template;
+ if in_tag {
+ if tag_token_pos > NAMED_TAG {
+ pos = find(bytes, pos, |rest| memchr2(b'<', b'>', rest));
+ } else if !is_token_start {
+ let run = run_until(bytes, pos, &TAG_DELIMITERS);
+ if run > 0 {
+ pos += run;
+ token_end = pos - 1;
+ }
+ }
+ } else if hidden {
+ pos = find(bytes, pos, |rest| memchr(b'<', rest));
+ } else {
+ let run = run_until(bytes, pos, &TEXT_DELIMITERS);
+ if run > 0 {
+ if is_token_start {
+ token_start = pos;
+ is_token_start = false;
+ }
+ pos += run;
+ token_end = pos - 1;
+ }
+ }
+ let Some(&ch) = bytes.get(pos) else {
+ break;
+ };
+ match ch {
+ b'<' => {
+ if !in_tag && !hidden && !is_token_start {
+ if sink.emit(token_start, token_end + 1, is_after_space) {
+ return true;
+ }
+ is_after_space = false;
+ }
+ tag_token_pos = 0;
+ in_tag = true;
+ is_token_start = true;
+ is_tag_close = false;
+ pos += 1;
+ continue;
+ }
+ b'>' if in_tag => {
+ if tag_token_pos == NAMED_TAG
+ && let Some(tag) = bytes.get(token_start..token_end + 1)
+ {
+ if tag.eq_ignore_ascii_case(b"br")
+ || (is_tag_close && tag.eq_ignore_ascii_case(b"p"))
+ {
+ if sink.newline() {
+ return true;
+ }
+ is_after_space = false;
+ is_new_line = true;
+ } else if tag.eq_ignore_ascii_case(b"head") {
+ in_head = !is_tag_close;
+ } else if tag.eq_ignore_ascii_case(b"style") {
+ in_style = !is_tag_close;
+ } else if tag.eq_ignore_ascii_case(b"script") {
+ in_script = !is_tag_close;
+ } else if tag.eq_ignore_ascii_case(b"template") {
+ in_template = !is_tag_close;
+ }
+ }
+ in_tag = false;
+ is_token_start = true;
+ pos += 1;
+ continue;
+ }
+ b'/' if in_tag => {
+ if tag_token_pos == 0 {
+ is_tag_close = true;
+ }
+ pos += 1;
+ continue;
+ }
+ b'!' if in_tag
+ && tag_token_pos == 0
+ && bytes.get(pos + 1..pos + 1 + COMMENT_OPEN.len()) == Some(COMMENT_OPEN) =>
+ {
+ let Some(close) = comment_close(bytes, pos + 1) else {
+ break;
+ };
+ in_tag = false;
+ is_token_start = true;
+ pos = close + 1;
+ continue;
+ }
+ b' ' | b'\t' | b'\r' | b'\n' => {
+ if !in_tag && !hidden {
+ if !is_token_start {
+ if sink.emit(token_start, token_end + 1, is_after_space && !is_new_line) {
+ return true;
+ }
+ is_new_line = false;
+ }
+ is_after_space = true;
+ }
+ is_token_start = true;
+ pos += 1;
+ continue;
+ }
+ b'&' if !in_tag && !is_token_start && !in_head => {
+ if in_style || in_script || in_template {
+ pos += 1;
+ continue;
+ }
+ if sink.emit(token_start, token_end + 1, is_after_space && !is_new_line) {
+ return true;
+ }
+ is_new_line = false;
+ is_token_start = true;
+ is_after_space = false;
+ }
+ b';' if !in_tag && !is_token_start && !in_head => {
+ if in_style || in_script || in_template {
+ pos += 1;
+ continue;
+ }
+ if sink.emit(token_start, pos + 1, is_after_space && !is_new_line) {
+ return true;
+ }
+ is_token_start = true;
+ is_after_space = false;
+ is_new_line = false;
+ pos += 1;
+ continue;
+ }
+ _ => (),
+ }
+ if is_token_start {
+ token_start = pos;
+ is_token_start = false;
+ if in_tag {
+ tag_token_pos += 1;
+ }
+ }
+ token_end = pos;
+ pos += 1;
+ }
+
+ if !in_tag && !is_token_start && !(in_head || in_style || in_script || in_template) {
+ sink.emit(token_start, token_end + 1, is_after_space && !is_new_line);
+ }
+ sink.flush();
+ false
+}
+
+fn find(bytes: &[u8], pos: usize, search: impl Fn(&[u8]) -> Option) -> usize {
+ bytes
+ .get(pos..)
+ .and_then(search)
+ .map_or(bytes.len(), |offset| pos + offset)
+}
+
+fn run_until(bytes: &[u8], pos: usize, delimiters: &[bool; 256]) -> usize {
+ let rest = bytes.get(pos..).unwrap_or_default();
+ rest.iter()
+ .position(|&byte| delimiters[usize::from(byte)])
+ .unwrap_or(rest.len())
+}
+
+fn comment_close(bytes: &[u8], comment_start: usize) -> Option {
+ let mut pos = comment_start;
+ loop {
+ let close = pos + memchr(b'>', bytes.get(pos..)?)?;
+ let dashes = bytes
+ .get(comment_start..close)
+ .unwrap_or_default()
+ .iter()
+ .rev()
+ .take(COMMENT_CLOSE_DASHES + 1)
+ .take_while(|&&byte| byte == b'-')
+ .count();
+ if dashes == COMMENT_CLOSE_DASHES {
+ return Some(close);
+ }
+ pos = close + 1;
+ }
+}
+
+struct Sink<'x, 'o> {
+ input: &'x str,
+ bytes: &'x [u8],
+ out: &'o mut String,
+ mode: Mode,
+ pending_start: usize,
+ pending_end: usize,
+}
+
+impl Sink<'_, '_> {
+ fn emit(&mut self, start: usize, end: usize, add_space: bool) -> bool {
+ let Some(token) = self.input.get(start..end) else {
+ return false;
+ };
+ if let Some(ch) = decode_entity(token) {
+ self.flush();
+ if add_space {
+ self.out.push(' ');
+ }
+ if ch != '\r' || self.mode == Mode::Complete {
+ self.out.push(ch);
+ }
+ return self.limit_reached();
+ }
+ let span_start = match start.checked_sub(1) {
+ Some(space) if add_space && self.bytes.get(space) == Some(&b' ') => space,
+ _ if add_space => {
+ self.flush();
+ self.out.push(' ');
+ start
+ }
+ _ => start,
+ };
+ if self.pending_start < self.pending_end && self.pending_end == span_start {
+ self.pending_end = end;
+ } else {
+ self.flush();
+ self.pending_start = span_start;
+ self.pending_end = end;
+ }
+ self.limit_reached()
+ }
+
+ fn newline(&mut self) -> bool {
+ self.flush();
+ self.out.push('\n');
+ self.limit_reached()
+ }
+
+ fn limit_reached(&mut self) -> bool {
+ let Mode::Preview { limit } = self.mode else {
+ return false;
+ };
+ let reached = self.out.len() + (self.pending_end - self.pending_start) > limit;
+ if reached {
+ self.flush();
+ }
+ reached
+ }
+
+ fn flush(&mut self) {
+ if let Some(pending) = self.input.get(self.pending_start..self.pending_end) {
+ self.out.push_str(pending);
+ }
+ self.pending_start = self.pending_end;
+ }
+}
diff --git a/src/decoders/mod.rs b/src/decoders/mod.rs
index e5f8a28..36df74a 100644
--- a/src/decoders/mod.rs
+++ b/src/decoders/mod.rs
@@ -4,16 +4,310 @@
* SPDX-License-Identifier: Apache-2.0 OR MIT
*/
+//! Decoders the parser uses that are also useful on their own: charset
+//! conversion, HTML to text and text to HTML, and body previews. Transfer
+//! encodings (base64, quoted-printable, hex) are decoded by encodify; use
+//! it directly for those.
+
+pub mod charsets;
+pub mod html;
+mod prefix;
+pub mod preview;
+
+use crate::Encoding;
+use charsets::Charset;
+use encodify::{base64, qp};
use std::borrow::Cow;
-use crate::parsers::MessageStream;
+pub(crate) use prefix::{Limit, TextPrefix, text_prefix};
-pub mod base64;
-pub mod charsets;
-pub mod encoded_word;
-pub mod hex;
-pub mod html;
-pub mod quoted_printable;
+const KNOWN_TRANSFER_ENCODINGS: [&[u8]; 5] =
+ [b"7bit", b"8bit", b"binary", b"base64", b"quoted-printable"];
-pub type DecodeFnc<'x> = fn(&mut MessageStream<'x>, &[u8]) -> (usize, Cow<'x, [u8]>);
-pub type DecodeWordFnc<'x> = fn(&mut MessageStream<'x>) -> Option>;
+pub(crate) fn transfer_decode(bytes: &[u8], encoding: Encoding) -> Cow<'_, [u8]> {
+ match encoding {
+ Encoding::None => Cow::Borrowed(bytes),
+ Encoding::QuotedPrintable => qp::BODY.decode(bytes).unwrap_or(Cow::Borrowed(bytes)),
+ Encoding::Base64 => {
+ let mut out = Vec::new();
+ transfer_decode_append(bytes, encoding, &mut out);
+ Cow::Owned(out)
+ }
+ }
+}
+
+pub(crate) fn transfer_decode_checked(bytes: &[u8], encoding: Encoding) -> (Cow<'_, [u8]>, bool) {
+ match encoding {
+ Encoding::None => (Cow::Borrowed(bytes), false),
+ Encoding::QuotedPrintable => match qp::BODY.strict().decode(bytes) {
+ Ok(decoded) => (decoded, false),
+ Err(_) => (transfer_decode(bytes, encoding), true),
+ },
+ Encoding::Base64 => {
+ let mut out = Vec::new();
+ let malformed = base64::MIME.decode_append(bytes, &mut out).is_err();
+ if malformed {
+ base64_tolerant(bytes, &mut out);
+ }
+ (Cow::Owned(out), malformed)
+ }
+ }
+}
+
+pub(crate) fn is_known_transfer_encoding(value: &[u8]) -> bool {
+ let token = value
+ .split(|&byte| byte == b'(')
+ .next()
+ .unwrap_or_default()
+ .trim_ascii();
+ KNOWN_TRANSFER_ENCODINGS
+ .iter()
+ .any(|known| token.eq_ignore_ascii_case(known))
+}
+
+pub(crate) fn transfer_decode_append(bytes: &[u8], encoding: Encoding, out: &mut Vec) {
+ match encoding {
+ Encoding::None => out.extend_from_slice(bytes),
+ Encoding::QuotedPrintable => {
+ if qp::BODY.decode_append(bytes, out).is_err() {
+ out.extend_from_slice(bytes);
+ }
+ }
+ Encoding::Base64 => {
+ if base64::MIME.decode_append(bytes, out).is_err() {
+ base64_tolerant(bytes, out);
+ }
+ }
+ }
+}
+
+pub(crate) fn transfer_decoded_len(bytes: &[u8], encoding: Encoding) -> usize {
+ match encoding {
+ Encoding::None => bytes.len(),
+ Encoding::Base64 => base64::MIME.decoded_len(bytes).unwrap_or_else(|_| {
+ let mut out = Vec::new();
+ base64_tolerant(bytes, &mut out);
+ out.len()
+ }),
+ Encoding::QuotedPrintable => qp::BODY.decoded_len(bytes).unwrap_or(bytes.len()),
+ }
+}
+
+fn base64_tolerant(rest: &[u8], out: &mut Vec) {
+ base64_feed(rest, out).finish(out);
+}
+
+fn base64_feed(mut rest: &[u8], out: &mut Vec) -> base64::Decoder {
+ let mut decoder = base64::MIME.decoder();
+ loop {
+ rest = rest
+ .get(decoder.decode_symbols(rest, out)..)
+ .unwrap_or_default();
+ match rest.split_first() {
+ None => return decoder,
+ Some((b'=', tail)) => {
+ decoder.pad(out);
+ rest = tail;
+ }
+ Some((_, tail)) => rest = tail,
+ }
+ }
+}
+
+pub(crate) fn charset(label: Option<&str>) -> Charset {
+ label
+ .and_then(|label| Charset::from_label(label.as_bytes()))
+ .unwrap_or_default()
+}
+
+pub(crate) fn rewrite<'x>(
+ text: Cow<'x, str>,
+ rewrite: impl for<'a> FnOnce(&'a str) -> Cow<'a, str>,
+) -> Cow<'x, str> {
+ match text {
+ Cow::Borrowed(text) => rewrite(text),
+ Cow::Owned(text) => {
+ let rewritten = match rewrite(&text) {
+ Cow::Owned(rewritten) => Some(rewritten),
+ Cow::Borrowed(same) if same.len() == text.len() => None,
+ Cow::Borrowed(other) => Some(other.to_owned()),
+ };
+ Cow::Owned(rewritten.unwrap_or(text))
+ }
+ }
+}
+
+pub(crate) fn to_text<'x>(bytes: Cow<'x, [u8]>, charset: Charset) -> Cow<'x, str> {
+ match bytes {
+ Cow::Borrowed(bytes) => charset.decode(bytes),
+ Cow::Owned(bytes) => Cow::Owned(charset.decode_owned(bytes)),
+ }
+}
+
+pub(crate) fn to_text_checked<'x>(bytes: Cow<'x, [u8]>, charset: Charset) -> (Cow<'x, str>, bool) {
+ match bytes {
+ Cow::Borrowed(bytes) => charset.decode_checked(bytes),
+ Cow::Owned(bytes) => {
+ let (text, malformed) = charset.decode_owned_checked(bytes);
+ (Cow::Owned(text), malformed)
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::scan::tests::Rng;
+
+ #[test]
+ fn qp_matches_codec() {
+ let alphabet = b"ab \t\r\n=\xc3\xa9";
+ let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
+ for _ in 0..20_000 {
+ let len = rng.below(24);
+ let input: Vec = (0..len)
+ .map(|_| {
+ alphabet
+ .get(rng.below(alphabet.len()))
+ .copied()
+ .unwrap_or(b'a')
+ })
+ .collect();
+ let mut decoded = Vec::new();
+ qp::BODY
+ .decode_append(&input, &mut decoded)
+ .expect("never fails");
+ let borrowed = transfer_decode(&input, Encoding::QuotedPrintable);
+ assert_eq!(borrowed.as_ref(), decoded.as_slice(), "{input:?}");
+ if matches!(borrowed, Cow::Borrowed(_)) {
+ assert_eq!(decoded, input);
+ }
+ assert_eq!(
+ transfer_decoded_len(&input, Encoding::QuotedPrintable),
+ decoded.len()
+ );
+ }
+ assert!(matches!(
+ transfer_decode(b"plain text\r\nline two\nend", Encoding::QuotedPrintable),
+ Cow::Borrowed(_)
+ ));
+ assert!(matches!(
+ transfer_decode(b"trailing \r\n", Encoding::QuotedPrintable),
+ Cow::Owned(_)
+ ));
+ }
+
+ #[test]
+ fn base64_best_effort() {
+ assert_eq!(
+ transfer_decode(b"SGVs\r\nbG8=", Encoding::Base64).as_ref(),
+ b"Hello"
+ );
+ assert_eq!(
+ transfer_decode(b"SGVs-bG8=", Encoding::Base64).as_ref(),
+ b"Hello"
+ );
+ assert_eq!(
+ transfer_decode(b"VGVzdA", Encoding::Base64).as_ref(),
+ b"Test"
+ );
+ assert_eq!(transfer_decoded_len(b"SGVs-bG8=", Encoding::Base64), 5);
+ assert_eq!(transfer_decoded_len(b"SGVsbG8=", Encoding::Base64), 5);
+ }
+
+ #[test]
+ fn checked_transfer_decoding() {
+ let alphabet = b"ab \t\r\n=\xc3\xa9AZ09+/-";
+ let mut rng = Rng(0x7ab5_c0de_1234_9876);
+ for _ in 0..20_000 {
+ let len = rng.below(24);
+ let input: Vec = (0..len)
+ .map(|_| {
+ alphabet
+ .get(rng.below(alphabet.len()))
+ .copied()
+ .unwrap_or(b'a')
+ })
+ .collect();
+ for encoding in [Encoding::None, Encoding::QuotedPrintable, Encoding::Base64] {
+ let (checked, malformed) = transfer_decode_checked(&input, encoding);
+ assert_eq!(checked, transfer_decode(&input, encoding), "{input:?}");
+ let expected = match encoding {
+ Encoding::None => false,
+ Encoding::QuotedPrintable => qp::BODY.strict().decoded_len(&input).is_err(),
+ Encoding::Base64 => base64::MIME.decoded_len(&input).is_err(),
+ };
+ assert_eq!(malformed, expected, "{encoding:?} {input:?}");
+ }
+ }
+ for (input, encoding, decoded, malformed) in [
+ (&b"SGVs\r\nbG8="[..], Encoding::Base64, &b"Hello"[..], false),
+ (b"SGVs-bG8=", Encoding::Base64, b"Hello", true),
+ (b"VGVzdA", Encoding::Base64, b"Test", false),
+ (
+ b"caf=C3=A9",
+ Encoding::QuotedPrintable,
+ b"caf\xc3\xa9",
+ false,
+ ),
+ (
+ b"soft=\r\nbreak",
+ Encoding::QuotedPrintable,
+ b"softbreak",
+ false,
+ ),
+ (b"a=ZZb", Encoding::QuotedPrintable, b"a=ZZb", true),
+ (b"end=4", Encoding::QuotedPrintable, b"end=4", true),
+ (b"as is=", Encoding::None, b"as is=", false),
+ ] {
+ let (checked, problem) = transfer_decode_checked(input, encoding);
+ assert_eq!(
+ (checked.as_ref(), problem),
+ (decoded, malformed),
+ "{input:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn known_transfer_encodings() {
+ for value in [
+ &b"7bit"[..],
+ b" 8BIT\r\n",
+ b"binary (comment)",
+ b"\r\n base64\r\n",
+ b" Quoted-Printable",
+ ] {
+ assert!(is_known_transfer_encoding(value), "{value:?}");
+ }
+ for value in [
+ &b"x-uuencode"[..],
+ b"",
+ b" base64;",
+ b"7-bit",
+ b"\"base64\"",
+ ] {
+ assert!(!is_known_transfer_encoding(value), "{value:?}");
+ }
+ }
+
+ #[test]
+ fn text_conversion() {
+ assert!(matches!(
+ to_text(Cow::Borrowed(b"caf\xc3\xa9"), charset(Some("utf-8"))),
+ Cow::Borrowed("café")
+ ));
+ assert_eq!(
+ to_text(Cow::Borrowed(b"caf\xe9"), charset(Some("iso-8859-1"))),
+ "café"
+ );
+ assert_eq!(
+ to_text(Cow::Owned(b"caf\xe9".to_vec()), charset(None)),
+ "caf\u{fffd}"
+ );
+ assert_eq!(
+ to_text(Cow::Owned(b"caf\xe9".to_vec()), charset(Some("x-unknown"))),
+ "caf\u{fffd}"
+ );
+ }
+}
diff --git a/src/decoders/prefix.rs b/src/decoders/prefix.rs
new file mode 100644
index 0000000..e0901ae
--- /dev/null
+++ b/src/decoders/prefix.rs
@@ -0,0 +1,117 @@
+/*
+ * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC
+ *
+ * SPDX-License-Identifier: Apache-2.0 OR MIT
+ */
+
+use super::{base64_feed, charsets::Charset, to_text, transfer_decode};
+use crate::Encoding;
+use encodify::qp;
+use memchr::memrchr;
+use std::borrow::Cow;
+
+const MAX_BYTES_PER_CHAR: usize = 4;
+const RAW_BYTES_PER_TEXT_BYTE: usize = 2;
+const INITIAL_SLACK: usize = 256;
+const GROWTH: usize = 4;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum Limit {
+ Chars(usize),
+ Bytes(usize),
+}
+
+pub(crate) struct TextPrefix<'x> {
+ pub(crate) text: Cow<'x, str>,
+ pub(crate) complete: bool,
+}
+
+pub(crate) fn text_prefix(
+ raw: &[u8],
+ encoding: Encoding,
+ charset: Charset,
+ limit: Limit,
+) -> TextPrefix<'_> {
+ let mut window = match limit {
+ Limit::Chars(chars) => chars.saturating_mul(MAX_BYTES_PER_CHAR),
+ Limit::Bytes(bytes) => bytes.saturating_mul(RAW_BYTES_PER_TEXT_BYTE),
+ }
+ .saturating_add(INITIAL_SLACK);
+ loop {
+ let whole = window >= raw.len();
+ let text = if whole {
+ to_text(transfer_decode(raw, encoding), charset)
+ } else {
+ let prefix = raw.get(..window).unwrap_or(raw);
+ decode_prefix(transfer_prefix(prefix, encoding), charset)
+ };
+ match limit {
+ Limit::Chars(chars) => {
+ if let Some(end) = char_start(&text, chars) {
+ return TextPrefix {
+ text: truncate(text, end),
+ complete: false,
+ };
+ }
+ }
+ Limit::Bytes(bytes) if text.len() > bytes => {
+ return TextPrefix {
+ text,
+ complete: whole,
+ };
+ }
+ Limit::Bytes(_) => (),
+ }
+ if whole {
+ return TextPrefix {
+ text,
+ complete: true,
+ };
+ }
+ window = window.saturating_mul(GROWTH);
+ }
+}
+
+fn char_start(text: &str, index: usize) -> Option {
+ if index >= text.len() {
+ None
+ } else if text.as_bytes().get(..index).is_some_and(<[u8]>::is_ascii) {
+ Some(index)
+ } else {
+ text.char_indices().nth(index).map(|(start, _)| start)
+ }
+}
+
+fn transfer_prefix(raw: &[u8], encoding: Encoding) -> Cow<'_, [u8]> {
+ match encoding {
+ Encoding::None => Cow::Borrowed(raw),
+ Encoding::QuotedPrintable => {
+ let lines = raw
+ .get(..memrchr(b'\n', raw).map_or(0, |end| end + 1))
+ .unwrap_or_default();
+ qp::BODY.decode(lines).unwrap_or(Cow::Borrowed(lines))
+ }
+ Encoding::Base64 => {
+ let mut out = Vec::with_capacity(raw.len() / 4 * 3 + 3);
+ base64_feed(raw, &mut out);
+ Cow::Owned(out)
+ }
+ }
+}
+
+fn decode_prefix(bytes: Cow<'_, [u8]>, charset: Charset) -> Cow<'_, str> {
+ match bytes {
+ Cow::Borrowed(bytes) => charset.decode_prefix(bytes),
+ Cow::Owned(bytes) => Cow::Owned(charset.decode_prefix(&bytes).into_owned()),
+ }
+}
+
+fn truncate(text: Cow<'_, str>, end: usize) -> Cow<'_, str> {
+ match text {
+ Cow::Borrowed(text) => Cow::Borrowed(text.get(..end).unwrap_or(text)),
+ Cow::Owned(mut text) => {
+ text.truncate(end);
+ Cow::Owned(text)
+ }
+ }
+}
diff --git a/src/decoders/preview.rs b/src/decoders/preview.rs
new file mode 100644
index 0000000..db4c4cb
--- /dev/null
+++ b/src/decoders/preview.rs
@@ -0,0 +1,308 @@
+/*
+ * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC
+ *
+ * SPDX-License-Identifier: Apache-2.0 OR MIT
+ */
+
+//! Previews and truncation of text and HTML bodies.
+
+use std::borrow::Cow;
+
+use memchr::memchr;
+
+use super::html::html_to_text_prefix;
+
+const ELLIPSIS: &str = "...";
+const MIN_LEN_WITH_ELLIPSIS: usize = 7;
+const COMMENT_OPEN: &[u8] = b"!--";
+const COMMENT_CLOSE: &[u8] = b"--";
+const LOOKAHEAD: usize = 4;
+const PREVIEW_SLACK: usize = 64;
+
+/// At most `max_len` bytes of `text`, carriage returns removed. Longer
+/// text is cut at a character boundary and, when `max_len` is 7 or more,
+/// ends with `...` (counted in `max_len`). Borrowed when the text fits and
+/// has no carriage return.
+///
+/// ```
+/// use mail_parser::preview_text;
+///
+/// assert_eq!(preview_text("Hello,\r\nworld", 20), "Hello,\nworld");
+/// assert_eq!(preview_text("Hello, world", 8), "Hello...");
+/// ```
+pub fn preview_text(text: &str, max_len: usize) -> Cow<'_, str> {
+ match strip_cr_prefix(text, max_len.saturating_add(1)) {
+ Stripped::Complete(text) if text.len() <= max_len => text,
+ Stripped::Complete(text) | Stripped::Prefix(text) => Cow::Owned(match text {
+ Cow::Borrowed(text) => truncate_chars(text, max_len),
+ Cow::Owned(text) => truncate_owned(text, max_len),
+ }),
+ }
+}
+
+/// A text preview of an HTML document: [`crate::html_to_text`] of the
+/// document cut like [`preview_text`]. Only the part of the document that
+/// the preview needs is converted.
+pub fn preview_html(html: &str, max_len: usize) -> String {
+ preview_html_prefix(html, max_len, true).unwrap_or_default()
+}
+
+pub(crate) fn preview_html_prefix(html: &str, max_len: usize, complete: bool) -> Option {
+ let mut text = String::with_capacity(max_len.saturating_add(PREVIEW_SLACK).min(html.len()));
+ if !html_to_text_prefix(html, max_len, &mut text) && !complete {
+ return None;
+ }
+ if text.len() > max_len {
+ let (keep, ellipsis) = cut(max_len);
+ text.truncate(text.floor_char_boundary(keep));
+ text.extend(ellipsis);
+ }
+ Some(text)
+}
+
+/// Truncates text for display; the same as [`preview_text`].
+pub fn truncate_text(text: &str, max_len: usize) -> Cow<'_, str> {
+ preview_text(text, max_len)
+}
+
+/// At most `max_len` bytes of an HTML document, carriage returns removed.
+/// A longer document is cut before a tag rather than inside one and, when
+/// `max_len` is 7 or more, ends with `...`. Borrowed when the document fits
+/// and has no carriage return.
+pub fn truncate_html(html: &str, max_len: usize) -> Cow<'_, str> {
+ match strip_cr_prefix(html, max_len.saturating_add(LOOKAHEAD)) {
+ Stripped::Complete(html) if html.len() <= max_len => html,
+ Stripped::Complete(html) | Stripped::Prefix(html) => {
+ Cow::Owned(truncate_markup(&html, max_len))
+ }
+ }
+}
+
+enum Stripped<'x> {
+ Complete(Cow<'x, str>),
+ Prefix(Cow<'x, str>),
+}
+
+fn strip_cr_prefix(text: &str, needed: usize) -> Stripped<'_> {
+ let window = text.as_bytes().get(..needed).unwrap_or(text.as_bytes());
+ if memchr(b'\r', window).is_none() {
+ return if text.len() < needed {
+ Stripped::Complete(Cow::Borrowed(text))
+ } else {
+ Stripped::Prefix(Cow::Borrowed(text))
+ };
+ }
+ let mut stripped = String::with_capacity(needed.min(text.len()));
+ let mut rest = text;
+ while stripped.len() < needed {
+ let missing = needed - stripped.len();
+ let window = rest.as_bytes().get(..missing).unwrap_or(rest.as_bytes());
+ match memchr(b'\r', window) {
+ Some(cr) => {
+ let (segment, tail) = rest.split_at(cr);
+ stripped.push_str(segment);
+ rest = tail.get(1..).unwrap_or_default();
+ }
+ None if rest.len() <= missing => {
+ stripped.push_str(rest);
+ return Stripped::Complete(Cow::Owned(stripped));
+ }
+ None => {
+ stripped.push_str(
+ rest.get(..rest.ceil_char_boundary(missing))
+ .unwrap_or_default(),
+ );
+ return Stripped::Prefix(Cow::Owned(stripped));
+ }
+ }
+ }
+ Stripped::Prefix(Cow::Owned(stripped))
+}
+
+fn cut(max_len: usize) -> (usize, Option<&'static str>) {
+ if max_len >= MIN_LEN_WITH_ELLIPSIS {
+ (max_len - ELLIPSIS.len(), Some(ELLIPSIS))
+ } else {
+ (max_len, None)
+ }
+}
+
+fn truncate_chars(text: &str, max_len: usize) -> String {
+ let (keep, ellipsis) = cut(max_len);
+ let kept = text
+ .get(..text.floor_char_boundary(keep))
+ .unwrap_or_default();
+ let mut result = String::with_capacity(kept.len() + ELLIPSIS.len());
+ result.push_str(kept);
+ result.extend(ellipsis);
+ result
+}
+
+fn truncate_owned(mut text: String, max_len: usize) -> String {
+ let (keep, ellipsis) = cut(max_len);
+ text.truncate(text.floor_char_boundary(keep));
+ text.extend(ellipsis);
+ text
+}
+
+fn truncate_markup(html: &str, max_len: usize) -> String {
+ let (keep, ellipsis) = cut(max_len);
+ let bytes = html.as_bytes();
+ let mut in_tag = false;
+ let mut in_comment = false;
+ let mut last_tag_end = 0;
+ let mut end = html.len();
+ for (pos, ch) in html.char_indices() {
+ let mut tag_boundary = 0;
+ match ch {
+ '<' if !in_tag => {
+ in_tag = true;
+ if bytes.get(pos + 1..pos + 1 + COMMENT_OPEN.len()) == Some(COMMENT_OPEN) {
+ in_comment = true;
+ }
+ tag_boundary = pos;
+ }
+ '>' if in_tag => {
+ if !in_comment {
+ in_tag = false;
+ tag_boundary = pos + 1;
+ } else if pos
+ .checked_sub(COMMENT_CLOSE.len())
+ .and_then(|start| bytes.get(start..pos))
+ == Some(COMMENT_CLOSE)
+ {
+ in_comment = false;
+ in_tag = false;
+ tag_boundary = pos + 1;
+ }
+ }
+ _ => (),
+ }
+ if ch.len_utf8() + pos > keep {
+ end = if (in_tag || tag_boundary > 0) && last_tag_end > 0 {
+ last_tag_end
+ } else {
+ pos
+ };
+ break;
+ } else if tag_boundary > 0 {
+ last_tag_end = tag_boundary;
+ }
+ }
+ let kept = html.get(..end).unwrap_or_default();
+ let mut result = String::with_capacity(kept.len() + ELLIPSIS.len());
+ result.push_str(kept);
+ result.extend(ellipsis);
+ result
+}
+
+#[cfg(test)]
+mod tests {
+ use std::borrow::Cow;
+
+ #[test]
+ fn text_preview() {
+ let text_1 = concat!(
+ "J'interdis aux marchands de vanter trop leurs marchandises. ",
+ "Car ils se fontvite pédagogues et t'enseignent comme but ce qui ",
+ "n'est par essence qu'un moyen, et te trompant ainsi sur la route ",
+ "à suivre les voilà bientôt qui te dégradent, car si leur musique ",
+ "est vulgaire ils te fabriquent pour te la vendre une âme vulgaire.\n",
+ "\u{2014} Antoine de Saint-Exupéry, Citadelle (1948)"
+ );
+ let text_2 = concat!(
+ "長沮、桀溺耦而耕,孔子過之,使子路問津焉。長沮曰:「夫執輿者為誰?」",
+ "子路曰:「為孔丘。」曰:「是魯孔丘與?」曰:「是也。」曰:「是知津矣。」問於桀溺,",
+ "桀溺曰:「子為誰?」曰:「為仲由。」曰:「是魯孔丘之徒與?」對曰:「然。",
+ "」曰:「滔滔者天下皆是也,而誰以易之?且而與其從辟人之士也,豈若從",
+ "辟世之士哉?」耰而不輟。子路行以告。夫子憮然曰:「鳥獸不可與同群,吾非斯人之徒",
+ "與而誰與?天下有道,丘不與易也。」",
+ "子路從而後,遇丈人,以杖荷蓧。子路問曰:「子見夫子乎?」丈人曰:「四體不勤,",
+ "五穀不分。孰為夫子?」植其杖而芸。子路拱而立。止子路宿,殺雞為黍而食之,見其二",
+ "子焉。明日,子路行以告。子曰:「隱者也。」使子路反見之。至則行矣。子路曰:「",
+ "不仕無義。長幼之節,不可廢也;君臣之義,如之何其廢之?欲潔其身,而亂大倫。君",
+ "子之仕也,行其義也。道之不行,已知之矣。」"
+ );
+
+ assert_eq!(
+ super::truncate_text(text_1, 110),
+ "J'interdis aux marchands de vanter trop leurs marchandises. Car ils se fontvite pédagogues et t'enseignent..."
+ );
+
+ assert_eq!(
+ super::truncate_text(text_2, 110),
+ "長沮、桀溺耦而耕,孔子過之,使子路問津焉。長沮曰:「夫執輿者為誰?」子..."
+ );
+ }
+
+ #[test]
+ fn html_truncate() {
+ for (html, expected_result) in [
+ (
+ "hello world ",
+ "hello world...",
+ ),
+ ("using <> ", "using <> ..."),
+ (
+ "test tag test tag ",
+ "test tag...",
+ ),
+ (
+ "<>< >>hello world< br \n />",
+ "<>< >>hello ...",
+ ),
+ (
+ concat!(
+ "ignore headxyz",
+ "
<body>
"
+ ),
+ "ignore he...",
+ ),
+ (
+ concat!(
+ "
what is ♥?
ßĂΒγ ",
+ "don't hurt me.
"
+ ),
+ "
what is ♥...",
+ ),
+ (
+ "the actual text",
+ "the a...",
+ ),
+ (
+ " < p > hello < / p > < p > world < / p > !!! < br > ",
+ " < p > hello ...",
+ ),
+ (
+ "