frontmatter_lossless/lib.rs
1//! Byte-exact Markdown frontmatter framing.
2//!
3//! A note is `---`-fenced YAML frontmatter followed by a body. This crate
4//! splits the two and joins them again without changing any byte the author
5//! wrote. The YAML text comes back as written (without the fences), with the
6//! byte offsets an edit needs, and [`compose`] rebuilds the original file
7//! exactly: the same BOM, the same `\n` or `\r\n` fences, and the same ending.
8//!
9//! It has no YAML parsing, no filesystem access, no regex, and nothing but
10//! `std`. Reading the frontmatter's values is a job for a YAML parser. This
11//! crate only finds where the block is and puts it back. It does not parse
12//! the body.
13//!
14//! It handles three cases that real notes contain:
15//!
16//! - **BOM.** Some Windows editors start a note with `\u{feff}---`. The split
17//! recognises the BOM and records it, so a later write can restore it.
18//! - **CRLF.** The `\r` stays in the YAML slice, so callers see the exact
19//! bytes. [`compose`] rebuilds `---\r\n` fences rather than rewriting them to
20//! `---\n`, which would change every line of the file in a diff.
21//! - **A missing or malformed closing fence is not an error.** An unterminated
22//! block is read as body, so code that reads thousands of notes keeps going
23//! instead of stopping at one bad note. [`split`] still flags it in
24//! [`Split::unterminated`] for a caller that wants to report the note as
25//! malformed.
26//!
27//! ```
28//! use frontmatter_lossless::split;
29//!
30//! let note = "---\ntitle: Hello\n---\n# Body\n";
31//! let s = split(note);
32//! assert_eq!(s.yaml, Some("title: Hello"));
33//! assert_eq!(s.body, "# Body\n");
34//! ```
35
36/// Line ending after the opening `---` fence.
37///
38/// A closed set. Adding a member would be a major release, so an exhaustive
39/// `match` over it is safe.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
41pub enum OpenEol {
42 /// A line feed, `\n`.
43 #[default]
44 Lf,
45 /// A carriage return and line feed, `\r\n`.
46 Crlf,
47}
48
49impl OpenEol {
50 /// The line ending as the bytes it stands for.
51 pub const fn as_str(self) -> &'static str {
52 match self {
53 OpenEol::Lf => "\n",
54 OpenEol::Crlf => "\r\n",
55 }
56 }
57}
58
59/// Line ending after the closing `---` fence.
60///
61/// A closed set, like [`OpenEol`], with one more member: [`CloseEol::None`],
62/// for a file that ended at its closing fence with no line ending after it.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum CloseEol {
65 /// No line ending: the file ended at the closing fence.
66 None,
67 /// A line feed, `\n`.
68 Lf,
69 /// A carriage return and line feed, `\r\n`.
70 Crlf,
71}
72
73impl CloseEol {
74 /// The line ending as the bytes it stands for. `""` for [`CloseEol::None`].
75 pub const fn as_str(self) -> &'static str {
76 match self {
77 CloseEol::None => "",
78 CloseEol::Lf => "\n",
79 CloseEol::Crlf => "\r\n",
80 }
81 }
82}
83
84/// Everything about a note's framing that a writer has to put back exactly.
85///
86/// Without it, a writer that edits the values carefully can still write `---\n`
87/// fences over a file whose fences were `---\r\n`. Then every line of the note
88/// shows as changed in git. The fences have to be kept too.
89///
90/// Take one from [`split`] and pass it back to [`compose`]. For a new note with
91/// no source text, take one from [`new_shape`]. The fields are public to read,
92/// but the type is `#[non_exhaustive]`. Build one with [`new_shape`], never a
93/// struct literal, so a later field is not a breaking change.
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95#[non_exhaustive]
96pub struct NoteShape {
97 /// The byte-order mark, if the file had one.
98 pub bom: bool,
99 /// Line ending after the opening `---`.
100 pub open_eol: OpenEol,
101 /// Line ending after the closing `---`. [`CloseEol::None`] when the file
102 /// ended there.
103 pub close_eol: CloseEol,
104 /// Whether the `\n` between the block's content and the closing `---` is
105 /// present. True for every block except the empty one with no line between
106 /// the fences (`---\n---`), where the closing fence directly follows the
107 /// opening fence's newline. It is a separate field because [`Split::yaml`]
108 /// alone cannot tell that block from one that holds only a blank line
109 /// (`---\n\n---`). Both give `Some("")`, but only the second has a
110 /// separator byte to restore.
111 pub close_sep: bool,
112}
113
114/// Options for [`new_shape`].
115///
116/// Construct it with [`Default`] and set the fields you need, so a later option
117/// is not a breaking change:
118///
119/// ```
120/// use frontmatter_lossless::{new_shape, NewShapeOptions, OpenEol};
121///
122/// let shape = new_shape(NewShapeOptions { eol: OpenEol::Crlf, ..Default::default() });
123/// assert_eq!(shape.open_eol, OpenEol::Crlf);
124/// ```
125#[derive(Debug, Clone, Copy, Default)]
126pub struct NewShapeOptions {
127 /// Line ending of both fences. Defaults to [`OpenEol::Lf`].
128 pub eol: OpenEol,
129 /// Whether the note starts with a byte-order mark. Defaults to `false`.
130 pub bom: bool,
131}
132
133/// A note split into its parts, with byte offsets into the original source.
134///
135/// The fields are public to read, but the type is `#[non_exhaustive]`. You get
136/// one from [`split`], never a struct literal, so a later field is not a
137/// breaking change.
138#[derive(Debug, Clone, PartialEq, Eq)]
139#[non_exhaustive]
140pub struct Split<'a> {
141 /// The frontmatter YAML, verbatim and without the `---` fences. `None`
142 /// when the note has no frontmatter block at all.
143 pub yaml: Option<&'a str>,
144 /// Byte range of `yaml` within the source (empty when `yaml` is `None`).
145 pub yaml_range: std::ops::Range<usize>,
146 /// Everything after the closing fence.
147 pub body: &'a str,
148 /// Byte offset of `body` within the source.
149 pub body_start: usize,
150 /// The framing to restore when writing this note back.
151 pub shape: NoteShape,
152 /// `true` when the note opens a frontmatter block that never closes: it
153 /// starts with a valid opening fence (`---` and a line break, after an
154 /// optional BOM) and no closing `---` line follows. `yaml` is still `None`
155 /// and `body` the whole text, as for a note with no block, so a reader of
156 /// many notes keeps going. A caller that requires valid frontmatter can
157 /// read this to report the note as malformed instead. `false` otherwise.
158 pub unterminated: bool,
159}
160
161/// The result of a tolerant read-only split: see [`split_lenient`].
162///
163/// The fields are public to read, but the type is `#[non_exhaustive]` so it can
164/// gain a field without breaking callers. Read `yaml` and `body` by name.
165#[derive(Debug, Clone, PartialEq, Eq)]
166#[non_exhaustive]
167pub struct LenientSplit<'a> {
168 /// The text between the fence lines, without the line break before the
169 /// closing fence.
170 pub yaml: &'a str,
171 /// Everything after the closing fence line.
172 pub body: &'a str,
173}
174
175const BOM: &str = "\u{feff}";
176
177/// The shape for a new note, one with no source text to [`split`]: both fences
178/// end in `opts.eol` and the closing fence has its line ending.
179///
180/// `compose(yaml, body, new_shape(NewShapeOptions::default()))` gives
181/// `---\n<yaml>\n---\n<body>`. The `yaml` argument is the text between the
182/// fences as [`split`] returns it, without the line break before the closing
183/// fence. A YAML serializer's output usually ends in one, so drop it first, or
184/// the block ends in a blank line. With `eol: OpenEol::Crlf`, [`compose`]
185/// writes the fences as CRLF and the yaml text keeps its own line endings, so
186/// end its lines in `\r\n` and the text itself in `\r`, as [`split`] returns a
187/// CRLF block.
188///
189/// ```
190/// use frontmatter_lossless::{compose, new_shape, NewShapeOptions};
191///
192/// let note = compose(Some("title: A"), "# A\n", new_shape(NewShapeOptions::default()));
193/// assert_eq!(note, "---\ntitle: A\n---\n# A\n");
194/// ```
195pub fn new_shape(opts: NewShapeOptions) -> NoteShape {
196 let close_eol = match opts.eol {
197 OpenEol::Lf => CloseEol::Lf,
198 OpenEol::Crlf => CloseEol::Crlf,
199 };
200 NoteShape {
201 bom: opts.bom,
202 open_eol: opts.eol,
203 close_eol,
204 close_sep: true,
205 }
206}
207
208/// Split a note into its frontmatter YAML and body.
209///
210/// Frontmatter is recognised only when the document begins with `---\n` (or
211/// `---\r\n`, or either after a BOM) and is closed by `---` alone on a line.
212/// Anything else, including a missing closing fence, is body. A missing closing
213/// fence also sets [`Split::unterminated`]. A leading BOM is part of the
214/// framing: it is recorded in [`Split::shape`] and left out of both `yaml` and
215/// `body`.
216///
217/// ```
218/// use frontmatter_lossless::split;
219///
220/// let s = split("---\na: 1\n---\nbody\n");
221/// assert_eq!(s.yaml, Some("a: 1"));
222/// assert_eq!(s.body, "body\n");
223/// assert!(!s.unterminated);
224///
225/// // An unterminated block is all body, and flagged.
226/// let u = split("---\na: 1\nno close\n");
227/// assert_eq!(u.yaml, None);
228/// assert!(u.unterminated);
229/// ```
230pub fn split(src: &str) -> Split<'_> {
231 let (bom, rest, offset) = match src.strip_prefix(BOM) {
232 Some(rest) => (true, rest, BOM.len()),
233 None => (false, src, 0),
234 };
235
236 // A BOM is framing, recorded in `shape` and excluded from `body`, so
237 // `body` is the content after it (`rest`, starting at `offset`).
238 let no_frontmatter = |unterminated: bool| Split {
239 yaml: None,
240 yaml_range: 0..0,
241 body: rest,
242 body_start: offset,
243 shape: NoteShape {
244 bom,
245 open_eol: OpenEol::Lf,
246 close_eol: CloseEol::Lf,
247 close_sep: true,
248 },
249 unterminated,
250 };
251
252 let (after_marker, marker_len, open_eol) = if let Some(r) = rest.strip_prefix("---\n") {
253 (r, 4, OpenEol::Lf)
254 } else if let Some(r) = rest.strip_prefix("---\r\n") {
255 (r, 5, OpenEol::Crlf)
256 } else {
257 return no_frontmatter(false);
258 };
259 let yaml_start = offset + marker_len;
260
261 // Empty frontmatter: the closing fence sits directly after the opener.
262 for (fence, len, close_eol) in [
263 ("---\n", 4usize, CloseEol::Lf),
264 ("---\r\n", 5, CloseEol::Crlf),
265 ] {
266 if let Some(r) = after_marker.strip_prefix(fence) {
267 return Split {
268 yaml: Some(""),
269 yaml_range: yaml_start..yaml_start,
270 body: r,
271 body_start: yaml_start + len,
272 shape: NoteShape {
273 bom,
274 open_eol,
275 close_eol,
276 close_sep: false,
277 },
278 unterminated: false,
279 };
280 }
281 }
282 if after_marker == "---" {
283 return Split {
284 yaml: Some(""),
285 yaml_range: yaml_start..yaml_start,
286 body: "",
287 body_start: src.len(),
288 shape: NoteShape {
289 bom,
290 open_eol,
291 close_eol: CloseEol::None,
292 close_sep: false,
293 },
294 unterminated: false,
295 };
296 }
297
298 let bytes = after_marker.as_bytes();
299 let mut search_start = 0usize;
300 loop {
301 let Some(found) = after_marker[search_start..].find("\n---") else {
302 // An opening fence with no closing one.
303 return no_frontmatter(true);
304 };
305 let dashes_start = search_start + found + 1;
306 let after_dashes = dashes_start + 3;
307 let (yaml_len, body_rel, close_eol) = match bytes.get(after_dashes).copied() {
308 None => (dashes_start - 1, after_marker.len(), CloseEol::None),
309 Some(b'\n') => (dashes_start - 1, after_dashes + 1, CloseEol::Lf),
310 Some(b'\r') if bytes.get(after_dashes + 1) == Some(&b'\n') => {
311 (dashes_start - 1, after_dashes + 2, CloseEol::Crlf)
312 }
313 _ => {
314 // `\n---foo` is not a terminator; keep looking.
315 search_start = after_dashes;
316 continue;
317 }
318 };
319 return Split {
320 yaml: Some(&after_marker[..yaml_len]),
321 yaml_range: yaml_start..yaml_start + yaml_len,
322 body: &after_marker[body_rel..],
323 body_start: yaml_start + body_rel,
324 shape: NoteShape {
325 bom,
326 open_eol,
327 close_eol,
328 close_sep: true,
329 },
330 unterminated: false,
331 };
332 }
333}
334
335/// Rebuild a note from a frontmatter block (possibly edited) and a body. This is
336/// the exact inverse of [`split`].
337///
338/// `frontmatter` mirrors [`Split::yaml`]: `None` is a note with no block (just
339/// the body, after any BOM), `Some("")` is an empty `---` / `---` block, and
340/// `Some(text)` is a block with content. Passing `split(src).yaml` straight
341/// back reproduces `src` byte for byte for every shape. New YAML or a new body
342/// always gets its own line, so a later [`split`] finds the block again.
343///
344/// ```
345/// use frontmatter_lossless::{compose, split};
346///
347/// let src = "---\r\na: 1\r\n---\r\nbody\r\n";
348/// let s = split(src);
349/// // Round-trips byte for byte, CRLF fences and all.
350/// assert_eq!(compose(s.yaml, s.body, s.shape), src);
351/// ```
352pub fn compose(frontmatter: Option<&str>, body: &str, shape: NoteShape) -> String {
353 let mut out = String::new();
354 if shape.bom {
355 out.push_str(BOM);
356 }
357 let Some(yaml) = frontmatter else {
358 // No block: the document is its body, after the BOM if there is one.
359 out.push_str(body);
360 return out;
361 };
362 out.push_str("---");
363 out.push_str(shape.open_eol.as_str());
364 out.push_str(yaml);
365 // Restore the separator that split removed before the closing fence: a
366 // single `\n`. (Under CRLF the block ends in a bare `\r`, so `\n`, not
367 // `open_eol`, rebuilds the original bytes.) The recorded shape decides
368 // this, not the yaml text: a block that ends in a blank line ends with
369 // `\n` and still had a separator after it. Only empty YAML can leave it
370 // out. Text written into a shape taken from an empty `---\n---` block still
371 // needs its own line before the closing fence.
372 if shape.close_sep || !yaml.is_empty() {
373 out.push('\n');
374 }
375 out.push_str("---");
376 // A shape from a file that ended at its closing fence has no line ending
377 // there. A new body still needs one, so use the opening fence's.
378 if shape.close_eol == CloseEol::None && !body.is_empty() {
379 out.push_str(shape.open_eol.as_str());
380 } else {
381 out.push_str(shape.close_eol.as_str());
382 }
383 out.push_str(body);
384 out
385}
386
387/// A tolerant, read-only frontmatter read for input that may be loosely
388/// written.
389///
390/// [`split`] is strict and lossless, and is the one to use before a write.
391/// This function also accepts things hand-written notes often contain and a
392/// reader can safely ignore: a leading BOM, blank lines or indentation before
393/// the opening fence, and trailing whitespace on the `---` fence lines. The
394/// closing fence must not be indented. It returns a [`LenientSplit`], or `None`
395/// when there is no block. It records no framing, so its result cannot be
396/// written back exactly. Use it to read, never to rewrite. A fence still closes
397/// only on `---` alone on its line (trailing whitespace aside), so a
398/// `---heading` in the body does not end the block.
399///
400/// ```
401/// use frontmatter_lossless::split_lenient;
402///
403/// let ls = split_lenient(" ---\ntitle: x\n--- \nbody\n").unwrap();
404/// assert_eq!(ls.yaml, "title: x");
405/// assert_eq!(ls.body, "body\n");
406/// assert!(split_lenient("no frontmatter\n").is_none());
407/// ```
408pub fn split_lenient(content: &str) -> Option<LenientSplit<'_>> {
409 let start = content.strip_prefix(BOM).unwrap_or(content).trim_start();
410 let (open, rest) = start.split_once('\n')?;
411 if open.trim_end() != "---" {
412 return None;
413 }
414 let mut offset = 0;
415 for line in rest.split_inclusive('\n') {
416 if line.trim_end() == "---" {
417 let raw = &rest[..offset];
418 let yaml = raw.strip_suffix('\n').unwrap_or(raw);
419 let yaml = yaml.strip_suffix('\r').unwrap_or(yaml);
420 return Some(LenientSplit {
421 yaml,
422 body: &rest[offset + line.len()..],
423 });
424 }
425 offset += line.len();
426 }
427 None
428}
429
430#[cfg(test)]
431mod tests {
432 use super::*;
433
434 fn lenient(content: &str) -> Option<(&str, &str)> {
435 split_lenient(content).map(|ls| (ls.yaml, ls.body))
436 }
437
438 #[test]
439 fn splits_a_plain_note() {
440 let s = split("---\ntitle: hi\n---\nbody\n");
441 assert_eq!(s.yaml, Some("title: hi"));
442 assert_eq!(s.body, "body\n");
443 assert!(!s.shape.bom);
444 assert!(!s.unterminated);
445 }
446
447 #[test]
448 fn a_note_with_no_frontmatter_is_all_body() {
449 let s = split("no fence here");
450 assert_eq!(s.yaml, None);
451 assert_eq!(s.body, "no fence here");
452 assert!(!s.unterminated);
453 }
454
455 #[test]
456 fn an_unterminated_block_is_all_body() {
457 let s = split("---\ntitle: hi\nstill going\n");
458 assert_eq!(s.yaml, None);
459 assert_eq!(s.body, "---\ntitle: hi\nstill going\n");
460 assert!(s.unterminated);
461 }
462
463 #[test]
464 fn a_fence_followed_by_other_text_does_not_close_the_block() {
465 let src = "---\na: 1\n---x\nb: 2\n---\nbody\n";
466 let s = split(src);
467 assert_eq!(s.yaml, Some("a: 1\n---x\nb: 2"));
468 assert_eq!(s.body, "body\n");
469 assert!(!s.unterminated);
470 assert_eq!(compose(s.yaml, s.body, s.shape), src);
471
472 // With no real closing fence after it, the block is unterminated.
473 let s = split("---\na: 1\n---x\n");
474 assert_eq!(s.yaml, None);
475 assert_eq!(s.body, "---\na: 1\n---x\n");
476 assert!(s.unterminated);
477
478 // A lone `\r` after the dashes is not a CRLF line end.
479 let s = split("---\na\n---\rb\n");
480 assert_eq!(s.yaml, None);
481 assert!(s.unterminated);
482 }
483
484 #[test]
485 fn crlf_keeps_the_carriage_return_on_the_yaml_side() {
486 let s = split("---\r\ntitle: hi\r\n---\r\nbody\r\n");
487 assert_eq!(s.yaml, Some("title: hi\r"));
488 assert_eq!(s.body, "body\r\n");
489 assert_eq!(s.shape.open_eol, OpenEol::Crlf);
490 assert_eq!(s.shape.close_eol, CloseEol::Crlf);
491 }
492
493 #[test]
494 fn a_bom_is_tolerated_and_remembered() {
495 let s = split("\u{feff}---\ntitle: hi\n---\nbody\n");
496 assert_eq!(s.yaml, Some("title: hi"));
497 assert_eq!(s.body, "body\n");
498 assert!(s.shape.bom);
499 }
500
501 #[test]
502 fn yaml_range_indexes_the_original_source() {
503 let src = "\u{feff}---\ntitle: hi\n---\nbody\n";
504 let s = split(src);
505 assert_eq!(&src[s.yaml_range.clone()], "title: hi");
506 assert_eq!(&src[s.body_start..], "body\n");
507 }
508
509 #[test]
510 fn empty_frontmatter_is_recognised() {
511 let s = split("---\n---\nbody\n");
512 assert_eq!(s.yaml, Some(""));
513 assert_eq!(s.body, "body\n");
514 assert!(!s.shape.close_sep);
515 }
516
517 #[test]
518 fn a_body_containing_a_fence_does_not_confuse_the_split() {
519 let s = split("---\na: 1\n---\nintro\n\n---\n\noutro\n");
520 assert_eq!(s.yaml, Some("a: 1"));
521 assert_eq!(s.body, "intro\n\n---\n\noutro\n");
522 }
523
524 #[test]
525 fn new_shape_defaults_to_lf_fences() {
526 let shape = new_shape(NewShapeOptions::default());
527 assert_eq!(shape.open_eol, OpenEol::Lf);
528 assert_eq!(shape.close_eol, CloseEol::Lf);
529 assert!(shape.close_sep);
530 assert!(!shape.bom);
531 assert_eq!(
532 compose(Some("title: A"), "# A\n", shape),
533 "---\ntitle: A\n---\n# A\n"
534 );
535 }
536
537 #[test]
538 fn new_shape_honours_crlf_and_bom() {
539 let shape = new_shape(NewShapeOptions {
540 eol: OpenEol::Crlf,
541 bom: true,
542 });
543 assert_eq!(shape.open_eol, OpenEol::Crlf);
544 assert_eq!(shape.close_eol, CloseEol::Crlf);
545 assert_eq!(
546 compose(Some("a: 1\r"), "b\r\n", shape),
547 "\u{feff}---\r\na: 1\r\n---\r\nb\r\n"
548 );
549 }
550
551 #[test]
552 fn compose_round_trips_a_split() {
553 for src in [
554 "---\na: 1\n---\nbody\n",
555 "\u{feff}---\na: 1\n---\nbody\n",
556 "just a body\n",
557 "\u{feff}just a body\n", // no block, with a BOM
558 "---\n---\nbody\n", // empty block, fences adjacent
559 "---\n\n---\nbody\n", // empty block, one blank line
560 "---\n\n\n---\nbody\n", // yaml is itself a blank line
561 "---\na: 1\n\n---\nbody\n", // yaml ends in a blank line
562 ] {
563 let s = split(src);
564 let out = compose(s.yaml, s.body, s.shape);
565 assert_eq!(out, src, "round trip failed for {src:?}");
566 }
567 }
568
569 #[test]
570 fn a_file_ending_at_the_closing_fence_round_trips() {
571 for src in ["---\na: 1\n---", "---\na: 1\n---\n", "---\r\na: 1\r\n---"] {
572 let s = split(src);
573 assert_eq!(compose(s.yaml, s.body, s.shape), src, "for {src:?}");
574 }
575 }
576
577 #[test]
578 fn yaml_written_into_an_empty_block_gets_its_own_line() {
579 for (src, yaml, want) in [
580 ("---\n---\nbody\n", "title: x", "---\ntitle: x\n---\nbody\n"),
581 (
582 "---\r\n---\r\nbody\r\n",
583 "title: x\r",
584 "---\r\ntitle: x\r\n---\r\nbody\r\n",
585 ),
586 ] {
587 let s = split(src);
588 let out = compose(Some(yaml), s.body, s.shape);
589 assert_eq!(out, want, "for {src:?}");
590 assert_eq!(split(&out).yaml, Some(yaml), "for {src:?}");
591 }
592 }
593
594 #[test]
595 fn a_body_added_after_a_closing_fence_at_the_end_gets_its_own_line() {
596 for (src, yaml, body, want) in [
597 (
598 "---\ntitle: x\n---",
599 "title: x",
600 "new\n",
601 "---\ntitle: x\n---\nnew\n",
602 ),
603 (
604 "---\r\ntitle: x\r\n---",
605 "title: x\r",
606 "new\r\n",
607 "---\r\ntitle: x\r\n---\r\nnew\r\n",
608 ),
609 ("---\n---", "", "new\n", "---\n---\nnew\n"),
610 ] {
611 let s = split(src);
612 let out = compose(Some(yaml), body, s.shape);
613 assert_eq!(out, want, "for {src:?}");
614 let back = split(&out);
615 assert_eq!((back.yaml, back.body), (Some(yaml), body), "for {src:?}");
616 }
617 }
618
619 #[test]
620 fn a_bom_without_frontmatter_is_framing_not_body() {
621 let s = split("\u{feff}just prose\n");
622 assert!(s.shape.bom);
623 assert_eq!(s.yaml, None);
624 assert_eq!(s.body, "just prose\n", "the BOM stays out of the body");
625 assert_eq!(compose(s.yaml, s.body, s.shape), "\u{feff}just prose\n");
626 }
627
628 #[test]
629 fn lenient_tolerates_leading_whitespace_and_fence_padding() {
630 assert_eq!(
631 lenient(" ---\ntitle: x\n---\nbody\n"),
632 Some(("title: x", "body\n"))
633 );
634 assert_eq!(
635 lenient("--- \ntitle: x\n--- \nbody\n"),
636 Some(("title: x", "body\n"))
637 );
638 assert_eq!(lenient("\u{feff}\n\n---\na: 1\n---\n"), Some(("a: 1", "")));
639 // CRLF, and an empty block.
640 assert_eq!(
641 lenient("---\r\na: 1\r\n---\r\nbody\r\n"),
642 Some(("a: 1", "body\r\n"))
643 );
644 assert_eq!(lenient("---\n---\nbody\n"), Some(("", "body\n")));
645 }
646
647 #[test]
648 fn lenient_returns_none_without_a_block() {
649 assert_eq!(lenient("no frontmatter\n"), None);
650 assert_eq!(lenient("---\nunterminated\n"), None);
651 assert_eq!(lenient(""), None);
652 }
653
654 #[test]
655 fn lenient_still_needs_a_bare_fence_to_close() {
656 assert_eq!(
657 lenient("---\na: 1\n---below\nb: 2\n---\nbody\n"),
658 Some(("a: 1\n---below\nb: 2", "body\n"))
659 );
660 }
661}