ferromark 0.1.2

Ultra-high-performance Markdown to HTML compiler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! HTML escaping utilities.
//!
//! Fast-path optimized: scans for first escapable character,
//! then bulk-copies segments between escapes.

use memchr::{memchr, memchr2, memchr3};

/// Characters that need escaping in HTML text content.
#[allow(dead_code)]
const TEXT_ESCAPE_CHARS: &[u8] = b"<>&";

/// Characters that need escaping in HTML attribute values.
#[allow(dead_code)]
const ATTR_ESCAPE_CHARS: &[u8] = b"<>&\"'";

/// Lookup table for escapable characters in text content.
/// Index by byte value, true if needs escaping.
/// Note: We escape " as &quot; for CommonMark spec compliance.
const TEXT_ESCAPE_TABLE: [bool; 256] = {
    let mut table = [false; 256];
    table[b'<' as usize] = true;
    table[b'>' as usize] = true;
    table[b'&' as usize] = true;
    table[b'"' as usize] = true;
    table
};

/// Lookup table for escapable characters in attributes.
const ATTR_ESCAPE_TABLE: [bool; 256] = {
    let mut table = [false; 256];
    table[b'<' as usize] = true;
    table[b'>' as usize] = true;
    table[b'&' as usize] = true;
    table[b'"' as usize] = true;
    table[b'\'' as usize] = true;
    table
};

/// Escape HTML text content into output buffer.
///
/// Escapes `<`, `>`, and `&` to their HTML entity equivalents.
///
/// # Example
/// ```
/// use ferromark::escape::escape_text_into;
///
/// let mut out = Vec::new();
/// escape_text_into(&mut out, b"<script>");
/// assert_eq!(out, b"&lt;script&gt;");
/// ```
#[inline]
pub fn escape_text_into(out: &mut Vec<u8>, input: &[u8]) {
    if input.is_empty() {
        return;
    }

    let mut start = 0usize;
    while let Some(rel) = first_text_escape(&input[start..]) {
        let pos = start + rel;
        if pos > start {
            out.extend_from_slice(&input[start..pos]);
        }
        push_text_escape(out, input[pos]);
        start = pos + 1;
    }
    if start < input.len() {
        out.extend_from_slice(&input[start..]);
    }
}

/// Escape HTML text content, checking for quotes as well (for attribute context).
///
/// This version handles all 5 escapable characters.
#[inline]
pub fn escape_full_into(out: &mut Vec<u8>, input: &[u8]) {
    if input.is_empty() {
        return;
    }

    let mut start = 0usize;
    while let Some(rel) = first_attr_escape(&input[start..]) {
        let pos = start + rel;
        if pos > start {
            out.extend_from_slice(&input[start..pos]);
        }
        push_attr_escape(out, input[pos]);
        start = pos + 1;
    }
    if start < input.len() {
        out.extend_from_slice(&input[start..]);
    }
}

/// Escape HTML attribute value into output buffer.
///
/// Escapes `<`, `>`, `&`, `"`, and `'` to their HTML entity equivalents.
///
/// # Example
/// ```
/// use ferromark::escape::escape_attr_into;
///
/// let mut out = Vec::new();
/// escape_attr_into(&mut out, b"value=\"test\"");
/// assert_eq!(out, b"value=&quot;test&quot;");
/// ```
#[inline]
pub fn escape_attr_into(out: &mut Vec<u8>, input: &[u8]) {
    escape_full_into(out, input)
}

/// Check if a byte slice needs any escaping for text content.
#[inline]
pub fn needs_text_escape(input: &[u8]) -> bool {
    input.iter().any(|&b| TEXT_ESCAPE_TABLE[b as usize])
}

/// Check if a byte slice needs any escaping for attribute values.
#[inline]
pub fn needs_attr_escape(input: &[u8]) -> bool {
    input.iter().any(|&b| ATTR_ESCAPE_TABLE[b as usize])
}

#[inline]
fn first_text_escape(input: &[u8]) -> Option<usize> {
    let a = memchr3(b'<', b'>', b'&', input);
    let b = memchr(b'"', input);
    min_opt(a, b)
}

#[inline]
fn first_attr_escape(input: &[u8]) -> Option<usize> {
    let a = memchr3(b'<', b'>', b'&', input);
    let b = memchr2(b'"', b'\'', input);
    min_opt(a, b)
}

#[inline]
fn min_opt(a: Option<usize>, b: Option<usize>) -> Option<usize> {
    match (a, b) {
        (Some(a), Some(b)) => Some(a.min(b)),
        (Some(a), None) => Some(a),
        (None, Some(b)) => Some(b),
        (None, None) => None,
    }
}

/// Escape and return as a new Vec.
///
/// Prefer `escape_text_into` to reuse buffers.
pub fn escape_text(input: &[u8]) -> Vec<u8> {
    let mut out = Vec::with_capacity(input.len() + input.len() / 8);
    escape_text_into(&mut out, input);
    out
}

/// Escape and return as a String.
///
/// Prefer `escape_text_into` to reuse buffers.
pub fn escape_text_to_string(input: &str) -> String {
    let escaped = escape_text(input.as_bytes());
    // SAFETY: We only add ASCII sequences, so if input was valid UTF-8,
    // output is also valid UTF-8
    unsafe { String::from_utf8_unchecked(escaped) }
}

/// URL percent-encode special characters, then HTML-escape for href attribute.
/// This is specifically for autolink URLs per CommonMark spec.
///
/// Check if a character is ASCII punctuation (can be backslash-escaped in URLs)
#[inline]
fn is_ascii_punctuation(b: u8) -> bool {
    matches!(
        b,
        b'!' | b'"'
            | b'#'
            | b'$'
            | b'%'
            | b'&'
            | b'\''
            | b'('
            | b')'
            | b'*'
            | b'+'
            | b','
            | b'-'
            | b'.'
            | b'/'
            | b':'
            | b';'
            | b'<'
            | b'='
            | b'>'
            | b'?'
            | b'@'
            | b'['
            | b'\\'
            | b']'
            | b'^'
            | b'_'
            | b'`'
            | b'{'
            | b'|'
            | b'}'
            | b'~'
    )
}

/// Process a link URL: decode entities, handle backslash escapes, and percent-encode.
/// This is used for link destinations in `[text](url)` syntax.
#[inline]
pub fn url_escape_link_destination(out: &mut Vec<u8>, input: &[u8]) {
    if memchr(b'&', input).is_none() {
        url_escape_link_destination_raw(out, input);
        return;
    }

    // First decode HTML entities
    let input_str = core::str::from_utf8(input).unwrap_or("");
    let decoded = html_escape::decode_html_entities(input_str);
    let decoded_bytes = decoded.as_bytes();

    url_escape_link_destination_raw(out, decoded_bytes);
}

#[inline]
fn push_text_escape(out: &mut Vec<u8>, b: u8) {
    match b {
        b'<' => out.extend_from_slice(b"&lt;"),
        b'>' => out.extend_from_slice(b"&gt;"),
        b'&' => out.extend_from_slice(b"&amp;"),
        b'"' => out.extend_from_slice(b"&quot;"),
        _ => out.push(b),
    }
}

#[inline]
fn push_attr_escape(out: &mut Vec<u8>, b: u8) {
    match b {
        b'<' => out.extend_from_slice(b"&lt;"),
        b'>' => out.extend_from_slice(b"&gt;"),
        b'&' => out.extend_from_slice(b"&amp;"),
        b'"' => out.extend_from_slice(b"&quot;"),
        b'\'' => out.extend_from_slice(b"&#39;"),
        _ => out.push(b),
    }
}

/// Process a link URL without entity decoding (used after entities are already decoded).
#[inline]
fn url_escape_link_destination_raw(out: &mut Vec<u8>, input: &[u8]) {
    const HEX: &[u8; 16] = b"0123456789ABCDEF";

    if input.is_ascii()
        && memchr2(b'\\', b' ', input).is_none()
        && memchr3(b'"', b'<', b'>', input).is_none()
        && memchr2(b'&', b'\'', input).is_none()
        && !input
            .iter()
            .any(|&b| matches!(b, 0x00..=0x08 | 0x0B | 0x0C | 0x0E..=0x1F | 0x7F))
    {
        out.extend_from_slice(input);
        return;
    }

    let mut pos = 0;
    while pos < input.len() {
        let b = input[pos];

        // Handle backslash escapes: \X where X is ASCII punctuation
        if b == b'\\' && pos + 1 < input.len() && is_ascii_punctuation(input[pos + 1]) {
            // Skip the backslash, encode the escaped character
            pos += 1;
            let escaped = input[pos];
            // The escaped character still needs HTML attribute escaping
            match escaped {
                b'<' => out.extend_from_slice(b"&lt;"),
                b'>' => out.extend_from_slice(b"&gt;"),
                b'&' => out.extend_from_slice(b"&amp;"),
                b'"' => out.extend_from_slice(b"%22"),
                b'\'' => out.extend_from_slice(b"&#39;"),
                _ => out.push(escaped),
            }
            pos += 1;
            continue;
        }

        // Handle characters that need encoding
        match b {
            // Characters that need URL percent-encoding
            b'\\' => out.extend_from_slice(b"%5C"),
            b' ' => out.extend_from_slice(b"%20"),
            b'"' => out.extend_from_slice(b"%22"),
            // Characters that need HTML escaping (but are valid in URLs)
            b'<' => out.extend_from_slice(b"&lt;"),
            b'>' => out.extend_from_slice(b"&gt;"),
            b'&' => out.extend_from_slice(b"&amp;"),
            b'\'' => out.extend_from_slice(b"&#39;"),
            // Control characters (0x00-0x1F except tab, LF, CR) and 0x7F
            0x00..=0x08 | 0x0B | 0x0C | 0x0E..=0x1F | 0x7F => {
                out.push(b'%');
                out.push(HEX[(b >> 4) as usize]);
                out.push(HEX[(b & 0xF) as usize]);
            }
            // Non-ASCII bytes need percent-encoding
            0x80..=0xFF => {
                out.push(b'%');
                out.push(HEX[(b >> 4) as usize]);
                out.push(HEX[(b & 0xF) as usize]);
            }
            // Everything else passes through
            _ => out.push(b),
        }
        pos += 1;
    }
}

/// Characters that need percent-encoding in URLs:
/// - Backslash `\` → `%5C`
/// - `[` → `%5B`
/// - `]` → `%5D`
/// - Backtick → `%60`
/// - Control characters
/// - Non-ASCII characters
#[inline]
pub fn url_encode_then_html_escape(out: &mut Vec<u8>, input: &[u8]) {
    const HEX: &[u8; 16] = b"0123456789ABCDEF";

    for &b in input {
        match b {
            // Characters that need URL percent-encoding
            b'\\' => out.extend_from_slice(b"%5C"),
            b'[' => out.extend_from_slice(b"%5B"),
            b']' => out.extend_from_slice(b"%5D"),
            b'`' => out.extend_from_slice(b"%60"),
            b' ' => out.extend_from_slice(b"%20"),
            // Characters that need HTML escaping
            b'<' => out.extend_from_slice(b"&lt;"),
            b'>' => out.extend_from_slice(b"&gt;"),
            b'&' => out.extend_from_slice(b"&amp;"),
            b'"' => out.extend_from_slice(b"&quot;"),
            b'\'' => out.extend_from_slice(b"&#39;"),
            // Control characters (0x00-0x1F except tab, LF, CR) and non-ASCII
            0x00..=0x08 | 0x0B | 0x0C | 0x0E..=0x1F | 0x80..=0xFF => {
                out.push(b'%');
                out.push(HEX[(b >> 4) as usize]);
                out.push(HEX[(b & 0xF) as usize]);
            }
            // Everything else passes through
            _ => out.push(b),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_escape_text_basic() {
        let mut out = Vec::new();
        escape_text_into(&mut out, b"Hello, World!");
        assert_eq!(out, b"Hello, World!");
    }

    #[test]
    fn test_escape_text_lt() {
        let mut out = Vec::new();
        escape_text_into(&mut out, b"<script>");
        assert_eq!(out, b"&lt;script&gt;");
    }

    #[test]
    fn test_escape_text_gt() {
        let mut out = Vec::new();
        escape_text_into(&mut out, b"1 > 0");
        assert_eq!(out, b"1 &gt; 0");
    }

    #[test]
    fn test_escape_text_amp() {
        let mut out = Vec::new();
        escape_text_into(&mut out, b"a & b");
        assert_eq!(out, b"a &amp; b");
    }

    #[test]
    fn test_escape_text_mixed() {
        let mut out = Vec::new();
        escape_text_into(&mut out, b"<a href=\"test\">link & stuff</a>");
        assert_eq!(
            out,
            b"&lt;a href=&quot;test&quot;&gt;link &amp; stuff&lt;/a&gt;"
        );
    }

    #[test]
    fn test_escape_text_empty() {
        let mut out = Vec::new();
        escape_text_into(&mut out, b"");
        assert_eq!(out, b"");
    }

    #[test]
    fn test_escape_attr_quotes() {
        let mut out = Vec::new();
        escape_full_into(&mut out, b"\"hello\"");
        assert_eq!(out, b"&quot;hello&quot;");
    }

    #[test]
    fn test_escape_attr_single_quote() {
        let mut out = Vec::new();
        escape_full_into(&mut out, b"it's");
        assert_eq!(out, b"it&#39;s");
    }

    #[test]
    fn test_escape_attr_all() {
        let mut out = Vec::new();
        escape_full_into(&mut out, b"<>&\"'");
        assert_eq!(out, b"&lt;&gt;&amp;&quot;&#39;");
    }

    #[test]
    fn test_needs_escape() {
        assert!(!needs_text_escape(b"hello"));
        assert!(needs_text_escape(b"<hello>"));
        assert!(needs_text_escape(b"a & b"));
        assert!(!needs_text_escape(b""));
    }

    #[test]
    fn test_escape_consecutive() {
        let mut out = Vec::new();
        escape_text_into(&mut out, b"<<<");
        assert_eq!(out, b"&lt;&lt;&lt;");
    }

    #[test]
    fn test_escape_at_boundaries() {
        let mut out = Vec::new();
        escape_text_into(&mut out, b"<");
        assert_eq!(out, b"&lt;");

        out.clear();
        escape_text_into(&mut out, b"hello<");
        assert_eq!(out, b"hello&lt;");

        out.clear();
        escape_text_into(&mut out, b"<hello");
        assert_eq!(out, b"&lt;hello");
    }

    #[test]
    fn test_escape_to_string() {
        let result = escape_text_to_string("<script>");
        assert_eq!(result, "&lt;script&gt;");
    }

    #[test]
    fn test_escape_unicode() {
        let mut out = Vec::new();
        escape_text_into(&mut out, "Hallo Welt! <tag>".as_bytes());
        assert_eq!(out, b"Hallo Welt! &lt;tag&gt;");
    }
}