ferromark 0.7.0

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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! Pointer-based cursor for high-performance byte scanning.
//!
//! Uses raw pointers internally for maximum scanning speed,
//! wrapped in a safe API with bounds checking at block entry.

use crate::Range;

/// A cursor for efficient byte-by-byte scanning.
///
/// Internally uses raw pointers to avoid bounds checks in tight loops.
/// The cursor is bounds-checked at creation and when advancing past known-safe regions.
///
/// # Example
/// ```
/// use ferromark::cursor::Cursor;
///
/// let input = b"Hello, World!";
/// let mut cursor = Cursor::new(input);
///
/// assert_eq!(cursor.peek(), Some(b'H'));
/// cursor.advance(7);
/// assert_eq!(cursor.peek(), Some(b'W'));
/// ```
#[derive(Clone, Copy)]
pub struct Cursor<'a> {
    ptr: *const u8,
    end: *const u8,
    base: *const u8,
    _marker: std::marker::PhantomData<&'a [u8]>,
}

impl<'a> Cursor<'a> {
    /// Create a new cursor over a byte slice.
    #[inline]
    pub fn new(input: &'a [u8]) -> Self {
        let ptr = input.as_ptr();
        let end = unsafe { ptr.add(input.len()) };
        Self {
            ptr,
            end,
            base: ptr,
            _marker: std::marker::PhantomData,
        }
    }

    /// Create a cursor starting at an offset.
    ///
    /// # Panics
    ///
    /// Panics if `offset` is past the end of `input`.
    #[inline]
    pub fn new_at(input: &'a [u8], offset: usize) -> Self {
        assert!(
            offset <= input.len(),
            "cursor offset {offset} exceeds input length {}",
            input.len()
        );
        let base = input.as_ptr();
        let ptr = unsafe { base.add(offset) };
        let end = unsafe { base.add(input.len()) };
        Self {
            ptr,
            end,
            base,
            _marker: std::marker::PhantomData,
        }
    }

    /// Current offset from the start of input.
    #[inline]
    pub fn offset(&self) -> usize {
        // SAFETY: ptr >= base by construction
        unsafe { self.ptr.offset_from(self.base) as usize }
    }

    /// Number of bytes remaining.
    #[inline]
    pub fn remaining(&self) -> usize {
        // SAFETY: end >= ptr by construction
        unsafe { self.end.offset_from(self.ptr) as usize }
    }

    /// Check if cursor is at end of input.
    #[inline]
    pub fn is_eof(&self) -> bool {
        self.ptr >= self.end
    }

    /// Peek the current byte without advancing.
    #[inline]
    pub fn peek(&self) -> Option<u8> {
        if self.is_eof() {
            None
        } else {
            // SAFETY: not at EOF
            Some(unsafe { *self.ptr })
        }
    }

    /// Peek the current byte, returning 0 at EOF.
    ///
    /// Useful for lookup tables where 0 is a sentinel.
    #[inline]
    pub fn peek_or_zero(&self) -> u8 {
        if self.is_eof() {
            0
        } else {
            unsafe { *self.ptr }
        }
    }

    /// Peek the current byte without bounds check.
    ///
    /// # Safety
    /// Caller must ensure cursor is not at EOF.
    #[inline]
    pub unsafe fn peek_unchecked(&self) -> u8 {
        debug_assert!(!self.is_eof());
        // SAFETY: Caller guarantees not at EOF
        unsafe { *self.ptr }
    }

    /// Peek at byte n positions ahead.
    #[inline]
    pub fn peek_ahead(&self, n: usize) -> Option<u8> {
        if n >= self.remaining() {
            None
        } else {
            // SAFETY: n < remaining
            Some(unsafe { *self.ptr.add(n) })
        }
    }

    /// Advance by n bytes.
    ///
    /// # Panics
    ///
    /// Panics if `n` exceeds the number of remaining bytes.
    #[inline]
    pub fn advance(&mut self, n: usize) {
        let remaining = self.remaining();
        assert!(
            n <= remaining,
            "cannot advance cursor by {n} bytes with only {remaining} remaining"
        );
        // SAFETY: The assertion above keeps the pointer within the allocation
        // or exactly one byte past its end.
        self.ptr = unsafe { self.ptr.add(n) };
    }

    /// Advance without checking the remaining length.
    ///
    /// This is crate-private so parser hot paths can avoid duplicate checks
    /// after their grammar logic has already established the bound.
    ///
    /// # Safety
    ///
    /// `n` must not exceed [`Self::remaining`].
    #[inline]
    pub(crate) unsafe fn advance_unchecked(&mut self, n: usize) {
        debug_assert!(n <= self.remaining());
        // SAFETY: The caller guarantees the resulting pointer stays within
        // the allocation or exactly one byte past its end.
        self.ptr = unsafe { self.ptr.add(n) };
    }

    /// Advance by 1 byte.
    ///
    /// # Panics
    ///
    /// Panics if the cursor is already at EOF.
    #[inline]
    pub fn bump(&mut self) {
        assert!(!self.is_eof(), "cannot bump cursor past EOF");
        // SAFETY: The assertion above guarantees one byte remains.
        self.ptr = unsafe { self.ptr.add(1) };
    }

    /// Advance by one byte without checking for EOF.
    ///
    /// # Safety
    ///
    /// The cursor must not be at EOF.
    #[inline]
    pub(crate) unsafe fn bump_unchecked(&mut self) {
        debug_assert!(!self.is_eof());
        // SAFETY: The caller guarantees one byte remains.
        self.ptr = unsafe { self.ptr.add(1) };
    }

    /// Consume and return current byte.
    #[inline]
    #[allow(clippy::should_implement_trait)]
    pub fn next(&mut self) -> Option<u8> {
        if self.is_eof() {
            None
        } else {
            // SAFETY: not at EOF
            let b = unsafe { *self.ptr };
            self.ptr = unsafe { self.ptr.add(1) };
            Some(b)
        }
    }

    /// Check if current position matches a byte.
    #[inline]
    pub fn at(&self, b: u8) -> bool {
        self.peek() == Some(b)
    }

    /// Check if current position matches any of the given bytes.
    #[inline]
    pub fn at_any(&self, bytes: &[u8]) -> bool {
        match self.peek() {
            Some(b) => bytes.contains(&b),
            None => false,
        }
    }

    /// Skip while predicate is true.
    #[inline]
    pub fn skip_while<F>(&mut self, mut predicate: F) -> usize
    where
        F: FnMut(u8) -> bool,
    {
        let start = self.offset();
        while let Some(b) = self.peek() {
            if !predicate(b) {
                break;
            }
            // SAFETY: `peek` returned a byte, so the cursor is not at EOF.
            unsafe { self.bump_unchecked() };
        }
        self.offset() - start
    }

    /// Skip whitespace (space and tab).
    #[inline]
    pub fn skip_whitespace(&mut self) -> usize {
        self.skip_while(|b| b == b' ' || b == b'\t')
    }

    /// Skip spaces only.
    #[inline]
    pub fn skip_spaces(&mut self) -> usize {
        self.skip_while(|b| b == b' ')
    }

    /// Consume a specific byte if present.
    #[inline]
    pub fn eat(&mut self, b: u8) -> bool {
        if self.at(b) {
            // SAFETY: `at` can only succeed when a byte remains.
            unsafe { self.bump_unchecked() };
            true
        } else {
            false
        }
    }

    /// Consume a specific byte sequence if present.
    #[inline]
    pub fn eat_bytes(&mut self, bytes: &[u8]) -> bool {
        if self.remaining() < bytes.len() {
            return false;
        }
        // SAFETY: remaining >= bytes.len()
        let slice = unsafe { std::slice::from_raw_parts(self.ptr, bytes.len()) };
        if slice == bytes {
            // SAFETY: The remaining-length check above covers `bytes.len()`.
            unsafe { self.advance_unchecked(bytes.len()) };
            true
        } else {
            false
        }
    }

    /// Get a range from a start offset to current position.
    #[inline]
    pub fn range_from(&self, start: usize) -> Range {
        Range::from_usize(start, self.offset())
    }

    /// Get the remaining bytes as a slice.
    #[inline]
    pub fn remaining_slice(&self) -> &'a [u8] {
        // SAFETY: ptr and end are valid pointers from the same allocation
        unsafe { std::slice::from_raw_parts(self.ptr, self.remaining()) }
    }

    /// Find the next occurrence of a byte using memchr.
    #[inline]
    pub fn find(&self, needle: u8) -> Option<usize> {
        memchr::memchr(needle, self.remaining_slice())
    }

    /// Find the next newline.
    #[inline]
    pub fn find_newline(&self) -> Option<usize> {
        self.find(b'\n')
    }

    /// Advance to the next newline, returning the range of the line (excluding newline).
    #[inline]
    pub fn consume_line(&mut self) -> Range {
        let start = self.offset();
        match self.find_newline() {
            Some(pos) => {
                let end = start + pos;
                // SAFETY: `pos` identifies a newline in the remaining slice.
                unsafe { self.advance_unchecked(pos + 1) }; // Skip past newline
                Range::from_usize(start, end)
            }
            None => {
                // No newline found, consume rest of input
                let end = start + self.remaining();
                let remaining = self.remaining();
                // SAFETY: Advancing by the exact remaining length reaches EOF.
                unsafe { self.advance_unchecked(remaining) };
                Range::from_usize(start, end)
            }
        }
    }
}

impl std::fmt::Debug for Cursor<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Cursor")
            .field("offset", &self.offset())
            .field("remaining", &self.remaining())
            .finish()
    }
}

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

    #[test]
    fn test_cursor_new() {
        let input = b"Hello";
        let cursor = Cursor::new(input);
        assert_eq!(cursor.offset(), 0);
        assert_eq!(cursor.remaining(), 5);
        assert!(!cursor.is_eof());
    }

    #[test]
    fn test_cursor_empty() {
        let cursor = Cursor::new(b"");
        assert_eq!(cursor.offset(), 0);
        assert_eq!(cursor.remaining(), 0);
        assert!(cursor.is_eof());
        assert_eq!(cursor.peek(), None);
    }

    #[test]
    fn test_cursor_peek() {
        let cursor = Cursor::new(b"abc");
        assert_eq!(cursor.peek(), Some(b'a'));
        assert_eq!(cursor.peek_ahead(0), Some(b'a'));
        assert_eq!(cursor.peek_ahead(1), Some(b'b'));
        assert_eq!(cursor.peek_ahead(2), Some(b'c'));
        assert_eq!(cursor.peek_ahead(3), None);
    }

    #[test]
    fn test_cursor_advance() {
        let mut cursor = Cursor::new(b"Hello");
        assert_eq!(cursor.peek(), Some(b'H'));

        cursor.advance(2);
        assert_eq!(cursor.offset(), 2);
        assert_eq!(cursor.peek(), Some(b'l'));

        cursor.bump();
        assert_eq!(cursor.offset(), 3);
        assert_eq!(cursor.peek(), Some(b'l'));
    }

    #[test]
    fn test_cursor_next() {
        let mut cursor = Cursor::new(b"abc");
        assert_eq!(cursor.next(), Some(b'a'));
        assert_eq!(cursor.next(), Some(b'b'));
        assert_eq!(cursor.next(), Some(b'c'));
        assert_eq!(cursor.next(), None);
    }

    #[test]
    fn test_cursor_at() {
        let cursor = Cursor::new(b"abc");
        assert!(cursor.at(b'a'));
        assert!(!cursor.at(b'b'));
        assert!(cursor.at_any(b"axy"));
        assert!(!cursor.at_any(b"xyz"));
    }

    #[test]
    fn test_cursor_skip_while() {
        let mut cursor = Cursor::new(b"   abc");
        let skipped = cursor.skip_spaces();
        assert_eq!(skipped, 3);
        assert_eq!(cursor.peek(), Some(b'a'));
    }

    #[test]
    fn test_cursor_skip_whitespace() {
        let mut cursor = Cursor::new(b" \t abc");
        let skipped = cursor.skip_whitespace();
        assert_eq!(skipped, 3);
        assert_eq!(cursor.peek(), Some(b'a'));
    }

    #[test]
    fn test_cursor_eat() {
        let mut cursor = Cursor::new(b"abc");
        assert!(cursor.eat(b'a'));
        assert!(!cursor.eat(b'a'));
        assert!(cursor.eat(b'b'));
    }

    #[test]
    fn test_cursor_eat_bytes() {
        let mut cursor = Cursor::new(b"hello world");
        assert!(cursor.eat_bytes(b"hello"));
        assert_eq!(cursor.peek(), Some(b' '));
        assert!(!cursor.eat_bytes(b"hello"));
        assert!(cursor.eat_bytes(b" world"));
        assert!(cursor.is_eof());
    }

    #[test]
    fn test_cursor_find() {
        let cursor = Cursor::new(b"hello\nworld");
        assert_eq!(cursor.find(b'\n'), Some(5));
        assert_eq!(cursor.find(b'x'), None);
    }

    #[test]
    fn test_cursor_consume_line() {
        let mut cursor = Cursor::new(b"line1\nline2\nline3");

        let line1 = cursor.consume_line();
        assert_eq!(line1.slice(b"line1\nline2\nline3"), b"line1");

        let line2 = cursor.consume_line();
        assert_eq!(line2.slice(b"line1\nline2\nline3"), b"line2");

        let line3 = cursor.consume_line();
        assert_eq!(line3.slice(b"line1\nline2\nline3"), b"line3");

        assert!(cursor.is_eof());
    }

    #[test]
    fn test_cursor_consume_line_no_trailing_newline() {
        let mut cursor = Cursor::new(b"hello");
        let line = cursor.consume_line();
        assert_eq!(line.slice(b"hello"), b"hello");
        assert!(cursor.is_eof());
    }

    #[test]
    fn test_cursor_range_from() {
        let mut cursor = Cursor::new(b"hello world");
        cursor.advance(6);
        let range = cursor.range_from(0);
        assert_eq!(range.start, 0);
        assert_eq!(range.end, 6);
    }

    #[test]
    fn test_cursor_new_at() {
        let input = b"hello world";
        let cursor = Cursor::new_at(input, 6);
        assert_eq!(cursor.offset(), 6);
        assert_eq!(cursor.peek(), Some(b'w'));
    }

    #[test]
    #[should_panic(expected = "cursor offset 2 exceeds input length 1")]
    fn new_at_panics_when_offset_exceeds_input() {
        let _ = Cursor::new_at(b"x", 2);
    }

    #[test]
    #[should_panic(expected = "cannot advance cursor by 2 bytes with only 1 remaining")]
    fn advance_panics_when_distance_exceeds_remaining_input() {
        let mut cursor = Cursor::new(b"x");
        cursor.advance(2);
    }

    #[test]
    #[should_panic(expected = "cannot bump cursor past EOF")]
    fn bump_panics_at_eof() {
        let mut cursor = Cursor::new(b"");
        cursor.bump();
    }
}