ferroni 1.0.0

Pure-Rust Oniguruma regex engine with SIMD-accelerated search
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
// regint.rs - Port of regint.h
// Internal types, OpCode, Operation, BitSet, MemStatus, regex_t.

use std::collections::HashMap;

use crate::oniguruma::*;
use crate::regenc::OnigEncoding;

// === Feature Flags (C #define USE_*) ===
pub const USE_CALL: bool = true;
pub const USE_CALLOUT: bool = true;
pub const USE_BACKREF_WITH_LEVEL: bool = true;
pub const USE_CAPTURE_HISTORY: bool = true;

// === Config Constants ===
pub const DEFAULT_PARSE_DEPTH_LIMIT: u32 = 4096;
pub const INIT_MATCH_STACK_SIZE: usize = 160;
pub const DEFAULT_MATCH_STACK_LIMIT_SIZE: u32 = 0;
pub const DEFAULT_RETRY_LIMIT_IN_MATCH: u64 = 10_000_000;
pub const DEFAULT_RETRY_LIMIT_IN_SEARCH: u64 = 0;
pub const DEFAULT_TIME_LIMIT_MSEC: u64 = 0;
pub const DEFAULT_SUBEXP_CALL_LIMIT_IN_SEARCH: u64 = 0;
pub const DEFAULT_SUBEXP_CALL_MAX_NEST_LEVEL: i32 = 20;

// === Internal Constants ===
pub const CHAR_MAP_SIZE: usize = 256;
pub const INFINITE_LEN: OnigLen = ONIG_INFINITE_DISTANCE;
pub const STEP_BACK_MAX_CHAR_LEN: i32 = 65535;
pub const LOOK_BEHIND_MAX_CHAR_LEN: i32 = STEP_BACK_MAX_CHAR_LEN;
pub const INFINITE_REPEAT: i32 = -1;

#[inline]
pub fn is_infinite_repeat(n: i32) -> bool {
    n == INFINITE_REPEAT
}

// === Bytecode Types ===
pub type RelAddrType = i32;
pub type AbsAddrType = i32;
pub type LengthType = i32;
pub type RelPositionType = i32;
pub type RepeatNumType = i32;
pub type MemNumType = i32;
pub type ModeType = i32;

// === MemStatus (bit status for captures) ===
pub type MemStatusType = u32;

pub const MEM_STATUS_BITS_NUM: usize = 32;

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mem_status_clear(stats: &mut MemStatusType) {
    *stats = 0;
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mem_status_on_all(stats: &mut MemStatusType) {
    *stats = !0u32;
}

#[inline]
pub fn mem_status_at(stats: MemStatusType, n: usize) -> bool {
    if n < MEM_STATUS_BITS_NUM {
        (stats & (1u32 << n)) != 0
    } else {
        (stats & 1) != 0
    }
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mem_status_at0(stats: MemStatusType, n: usize) -> bool {
    if n > 0 && n < MEM_STATUS_BITS_NUM {
        (stats & (1u32 << n)) != 0
    } else {
        (stats & 1) != 0
    }
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mem_status_is_all_on(stats: MemStatusType) -> bool {
    (stats & 1) != 0
}

#[inline]
pub fn mem_status_on(stats: &mut MemStatusType, n: usize) {
    if n < MEM_STATUS_BITS_NUM {
        if n != 0 {
            *stats |= 1u32 << n;
        }
    } else {
        *stats |= 1;
    }
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mem_status_on_simple(stats: &mut MemStatusType, n: usize) {
    if n < MEM_STATUS_BITS_NUM {
        *stats |= 1u32 << n;
    }
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mem_status_limit_at(stats: MemStatusType, n: usize) -> bool {
    if n < MEM_STATUS_BITS_NUM {
        (stats & (1u32 << n)) != 0
    } else {
        false
    }
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mem_status_limit_on(stats: &mut MemStatusType, n: usize) {
    if n < MEM_STATUS_BITS_NUM && n != 0 {
        *stats |= 1u32 << n;
    }
}

// === BitSet (256 bits for ASCII character classes) ===
pub const BITS_PER_BYTE: usize = 8;
pub const SINGLE_BYTE_SIZE: usize = 1 << BITS_PER_BYTE;
pub const BITS_IN_ROOM: usize = 32;
pub const BITSET_REAL_SIZE: usize = SINGLE_BYTE_SIZE / BITS_IN_ROOM;
pub type Bits = u32;
pub type BitSet = [Bits; BITSET_REAL_SIZE];

pub const SIZE_BITSET: usize = std::mem::size_of::<BitSet>();

#[inline]
pub fn bitset_clear(bs: &mut BitSet) {
    for i in 0..BITSET_REAL_SIZE {
        bs[i] = 0;
    }
}

#[inline]
pub fn bs_room(pos: usize) -> usize {
    pos >> 5
}

#[inline]
pub fn bs_bit(pos: usize) -> u32 {
    1u32 << (pos & 0x1f)
}

#[inline]
pub fn bitset_at(bs: &BitSet, pos: usize) -> bool {
    (bs[bs_room(pos)] & bs_bit(pos)) != 0
}

#[inline]
pub fn bitset_set_bit(bs: &mut BitSet, pos: usize) {
    bs[bs_room(pos)] |= bs_bit(pos);
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn bitset_clear_bit(bs: &mut BitSet, pos: usize) {
    bs[bs_room(pos)] &= !bs_bit(pos);
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn bitset_invert_bit(bs: &mut BitSet, pos: usize) {
    bs[bs_room(pos)] ^= bs_bit(pos);
}

// === Anchor Flags ===
pub const ANCR_PREC_READ: i32 = 1 << 0;
pub const ANCR_PREC_READ_NOT: i32 = 1 << 1;
pub const ANCR_LOOK_BEHIND: i32 = 1 << 2;
pub const ANCR_LOOK_BEHIND_NOT: i32 = 1 << 3;
pub const ANCR_BEGIN_BUF: i32 = 1 << 4;
pub const ANCR_BEGIN_LINE: i32 = 1 << 5;
pub const ANCR_BEGIN_POSITION: i32 = 1 << 6;
pub const ANCR_END_BUF: i32 = 1 << 7;
pub const ANCR_SEMI_END_BUF: i32 = 1 << 8;
pub const ANCR_END_LINE: i32 = 1 << 9;
pub const ANCR_WORD_BOUNDARY: i32 = 1 << 10;
pub const ANCR_NO_WORD_BOUNDARY: i32 = 1 << 11;
pub const ANCR_WORD_BEGIN: i32 = 1 << 12;
pub const ANCR_WORD_END: i32 = 1 << 13;
pub const ANCR_ANYCHAR_INF: i32 = 1 << 14;
pub const ANCR_ANYCHAR_INF_ML: i32 = 1 << 15;
pub const ANCR_TEXT_SEGMENT_BOUNDARY: i32 = 1 << 16;
pub const ANCR_NO_TEXT_SEGMENT_BOUNDARY: i32 = 1 << 17;
pub const ANCR_ANYCHAR_INF_MASK: i32 = ANCR_ANYCHAR_INF | ANCR_ANYCHAR_INF_ML;

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn anchor_has_body(anchor_type: i32) -> bool {
    anchor_type < ANCR_BEGIN_BUF
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn is_word_anchor_type(anchor_type: i32) -> bool {
    anchor_type == ANCR_WORD_BOUNDARY
        || anchor_type == ANCR_NO_WORD_BOUNDARY
        || anchor_type == ANCR_WORD_BEGIN
        || anchor_type == ANCR_WORD_END
}

// === OpCode Enum ===
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum OpCode {
    Finish = 0,
    End = 1,
    Str1 = 2,
    Str2 = 3,
    Str3 = 4,
    Str4 = 5,
    Str5 = 6,
    StrN = 7,
    StrMb2n1 = 8,
    StrMb2n2 = 9,
    StrMb2n3 = 10,
    StrMb2n = 11,
    StrMb3n = 12,
    StrMbn = 13,
    CClass = 14,
    CClassMb = 15,
    CClassMix = 16,
    CClassNot = 17,
    CClassMbNot = 18,
    CClassMixNot = 19,
    AnyChar = 20,
    AnyCharMl = 21,
    AnyCharStar = 22,
    AnyCharMlStar = 23,
    AnyCharStarPeekNext = 24,
    AnyCharMlStarPeekNext = 25,
    Word = 26,
    WordAscii = 27,
    NoWord = 28,
    NoWordAscii = 29,
    WordBoundary = 30,
    NoWordBoundary = 31,
    WordBegin = 32,
    WordEnd = 33,
    TextSegmentBoundary = 34,
    BeginBuf = 35,
    EndBuf = 36,
    BeginLine = 37,
    EndLine = 38,
    SemiEndBuf = 39,
    CheckPosition = 40,
    BackRef1 = 41,
    BackRef2 = 42,
    BackRefN = 43,
    BackRefNIc = 44,
    BackRefMulti = 45,
    BackRefMultiIc = 46,
    BackRefWithLevel = 47,
    BackRefWithLevelIc = 48,
    BackRefCheck = 49,
    BackRefCheckWithLevel = 50,
    MemStart = 51,
    MemStartPush = 52,
    MemEndPush = 53,
    MemEndPushRec = 54,
    MemEnd = 55,
    MemEndRec = 56,
    Fail = 57,
    Jump = 58,
    Push = 59,
    PushSuper = 60,
    Pop = 61,
    PopToMark = 62,
    PushOrJumpExact1 = 63,
    PushIfPeekNext = 64,
    Repeat = 65,
    RepeatNg = 66,
    RepeatInc = 67,
    RepeatIncNg = 68,
    EmptyCheckStart = 69,
    EmptyCheckEnd = 70,
    EmptyCheckEndMemst = 71,
    EmptyCheckEndMemstPush = 72,
    Move = 73,
    StepBackStart = 74,
    StepBackNext = 75,
    CutToMark = 76,
    Mark = 77,
    SaveVal = 78,
    UpdateVar = 79,
    Call = 80,
    Return = 81,
    CalloutContents = 82,
    CalloutName = 83,
}

// === SaveType ===
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(i32)]
pub enum SaveType {
    Keep = 0,
    S = 1,
    RightRange = 2,
}

// === UpdateVarType ===
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(i32)]
pub enum UpdateVarType {
    KeepFromStackLast = 0,
    SFromStack = 1,
    RightRangeFromStack = 2,
    RightRangeFromSStack = 3,
    RightRangeToS = 4,
    RightRangeInit = 5,
}

// === CheckPositionType ===
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(i32)]
pub enum CheckPositionType {
    SearchStart = 0,
    CurrentRightRange = 1,
}

// === TextSegmentBoundaryType ===
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(i32)]
pub enum TextSegmentBoundaryType {
    ExtendedGraphemeCluster = 0,
    Word = 1,
}

// === Stack Pop Level ===
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(i32)]
pub enum StackPopLevel {
    Free = 0,
    MemStart = 1,
    All = 2,
}

// === Optimize Type ===
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OptimizeType {
    None,
    Str,
    StrFast,
    StrFastStepForward,
    Map,
}

// === CClass Flags ===
pub const FLAG_NCCLASS_NOT: u32 = 1 << 0;
pub const FLAG_NCCLASS_SHARE: u32 = 1 << 1;

// === Operation (Bytecode Instruction) ===
//
// In C this is a struct with opcode + union. In Rust we use struct + enum payload.
// The opcode field is stored separately for direct access (needed for dispatch).
pub struct Operation {
    pub opcode: OpCode,
    pub payload: OperationPayload,
}

pub enum OperationPayload {
    None,
    Exact {
        s: [u8; 16],
    },
    ExactN {
        s: Vec<u8>,
        n: LengthType,
    },
    ExactLenN {
        s: Vec<u8>,
        n: LengthType,
        len: LengthType,
    },
    CClass {
        bsp: Box<BitSet>,
    },
    CClassMb {
        mb: Vec<u32>,
    },
    CClassMix {
        mb: Vec<u32>,
        bsp: Box<BitSet>,
    },
    AnyCharStarPeekNext {
        c: u8,
    },
    WordBoundary {
        mode: ModeType,
    },
    TextSegmentBoundary {
        boundary_type: TextSegmentBoundaryType,
        not: bool,
    },
    CheckPosition {
        check_type: CheckPositionType,
    },
    BackRefN {
        n1: MemNumType,
    },
    BackRefGeneral {
        num: i32,
        ns: Vec<MemNumType>,
        nest_level: i32,
    },
    MemoryStart {
        num: MemNumType,
    },
    MemoryEnd {
        num: MemNumType,
    },
    Jump {
        addr: RelAddrType,
    },
    Push {
        addr: RelAddrType,
    },
    PushOrJumpExact1 {
        addr: RelAddrType,
        c: u8,
    },
    PushIfPeekNext {
        addr: RelAddrType,
        c: u8,
    },
    PopToMark {
        id: MemNumType,
    },
    Repeat {
        id: MemNumType,
        addr: RelAddrType,
    },
    RepeatInc {
        id: MemNumType,
    },
    EmptyCheckStart {
        mem: MemNumType,
    },
    EmptyCheckEnd {
        mem: MemNumType,
        empty_status_mem: MemStatusType,
    },
    Move {
        n: RelPositionType,
    },
    StepBackStart {
        initial: LengthType,
        remaining: LengthType,
        addr: RelAddrType,
    },
    CutToMark {
        id: MemNumType,
        restore_pos: bool,
    },
    Mark {
        id: MemNumType,
        save_pos: bool,
    },
    SaveVal {
        save_type: SaveType,
        id: MemNumType,
    },
    UpdateVar {
        var_type: UpdateVarType,
        id: MemNumType,
        clear: bool,
    },
    Call {
        addr: AbsAddrType,
    },
    Return,
    CalloutContents {
        num: MemNumType,
    },
    CalloutName {
        num: MemNumType,
        id: MemNumType,
    },
}

// === Callout constants ===
pub const CALLOUT_IN_PROGRESS: i32 = OnigCalloutIn::Progress as i32;
pub const CALLOUT_IN_RETRACTION: i32 = OnigCalloutIn::Retraction as i32;
pub const CALLOUT_IN_BOTH: i32 = CALLOUT_IN_PROGRESS | CALLOUT_IN_RETRACTION;

/// Builtin callout IDs (hard-coded instead of global name registry)
pub const CALLOUT_BUILTIN_FAIL: i32 = 0;
pub const CALLOUT_BUILTIN_MAX: i32 = 1;
pub const CALLOUT_BUILTIN_COUNT: i32 = 2;
pub const CALLOUT_BUILTIN_CMP: i32 = 3;
pub const CALLOUT_BUILTIN_SKIP: i32 = 4;

/// Result codes for callout functions
pub const ONIG_CALLOUT_FAIL: i32 = 1;
pub const ONIG_CALLOUT_SUCCESS: i32 = 0;

// === Callout argument ===
#[derive(Clone, Debug)]
pub enum CalloutArg {
    Long(i64),
    Char(u8),
    Tag(Vec<u8>),
    Str(Vec<u8>),
}

// === CalloutListEntry ===
pub struct CalloutListEntry {
    pub of: i32,         // 0=contents, 1=name
    pub callout_in: i32, // CALLOUT_IN_PROGRESS / RETRACTION / BOTH
    pub builtin_id: i32, // CALLOUT_BUILTIN_MAX etc., -1 for contents
    pub tag: Option<Vec<u8>>,
    pub tag_start: usize, // byte offset of tag start in pattern
    pub tag_end: usize,   // byte offset of tag end in pattern
    pub args: Vec<CalloutArg>,
    pub content_end: Option<Vec<u8>>, // Content end bytes for content callouts
}

// === RepeatRange ===
#[derive(Clone, Debug)]
pub struct RepeatRange {
    pub lower: i32,
    pub upper: i32,
    pub u_offset: i32,
}

// === RegexExt (Callout Extension) ===
pub struct RegexExt {
    pub pattern: Vec<u8>,
    pub tag_table: Option<HashMap<Vec<u8>, i32>>,
    pub callout_num: i32,
    pub callout_list: Vec<CalloutListEntry>,
}

// === regex_t (re_pattern_buffer) ===
pub struct RegexType {
    // bytecode
    pub(crate) ops: Vec<Operation>,
    pub(crate) string_pool: Vec<u8>,

    // capture info
    pub(crate) num_mem: i32,
    pub(crate) num_repeat: i32,
    pub(crate) num_empty_check: i32,
    pub(crate) num_call: i32,
    pub(crate) capture_history: MemStatusType,
    pub(crate) push_mem_start: MemStatusType,
    pub(crate) push_mem_end: MemStatusType,
    pub(crate) stack_pop_level: StackPopLevel,
    pub(crate) repeat_range: Vec<RepeatRange>,

    // metadata
    pub(crate) enc: OnigEncoding,
    pub(crate) options: OnigOptionType,
    pub(crate) syntax: *const OnigSyntaxType,
    pub(crate) case_fold_flag: OnigCaseFoldType,
    pub(crate) name_table: Option<crate::regparse_types::NameTable>,

    // optimization
    pub(crate) optimize: OptimizeType,
    pub(crate) threshold_len: i32,
    pub(crate) anchor: i32,
    pub(crate) anc_dist_min: OnigLen,
    pub(crate) anc_dist_max: OnigLen,
    pub(crate) sub_anchor: i32,
    pub(crate) exact: Vec<u8>,
    pub(crate) map: [u8; CHAR_MAP_SIZE],
    pub(crate) map_offset: i32,
    pub(crate) map_bytes: [u8; 3],
    pub(crate) map_byte_count: u8,
    pub(crate) dist_min: OnigLen,
    pub(crate) dist_max: OnigLen,

    // subroutine call support
    pub(crate) called_addrs: Vec<i32>, // group_num -> called entry address
    pub(crate) unset_call_addrs: Vec<(usize, i32)>, // (op_index, group_num) for patching

    // extension (callouts)
    pub(crate) extp: Option<RegexExt>,
}

// === Optimization data structures ===
pub const OPT_EXACT_MAXLEN: usize = 24;

#[derive(Clone, Copy)]
pub struct MinMaxLen {
    pub min: OnigLen,
    pub max: OnigLen,
}

impl MinMaxLen {
    pub fn new() -> Self {
        MinMaxLen { min: 0, max: 0 }
    }

    pub fn clear(&mut self) {
        self.min = 0;
        self.max = 0;
    }

    pub fn set(&mut self, min: OnigLen, max: OnigLen) {
        self.min = min;
        self.max = max;
    }

    pub fn add(&mut self, other: &MinMaxLen) {
        self.min = crate::regcomp::distance_add(self.min, other.min);
        self.max = crate::regcomp::distance_add(self.max, other.max);
    }

    pub fn alt_merge(&mut self, other: &MinMaxLen) {
        if self.min > other.min {
            self.min = other.min;
        }
        if self.max < other.max {
            self.max = other.max;
        }
    }

    pub fn is_equal(&self, other: &MinMaxLen) -> bool {
        self.min == other.min && self.max == other.max
    }
}

#[derive(Clone, Copy)]
pub struct OptAnc {
    pub left: i32,
    pub right: i32,
}

impl OptAnc {
    pub fn new() -> Self {
        OptAnc { left: 0, right: 0 }
    }

    pub fn clear(&mut self) {
        self.left = 0;
        self.right = 0;
    }
}

#[derive(Clone, Copy)]
pub struct OptStr {
    pub mm: MinMaxLen,
    pub anc: OptAnc,
    pub reach_end: i32,
    pub len: usize,
    pub s: [u8; OPT_EXACT_MAXLEN],
}

impl OptStr {
    pub fn new() -> Self {
        OptStr {
            mm: MinMaxLen::new(),
            anc: OptAnc::new(),
            reach_end: 0,
            len: 0,
            s: [0u8; OPT_EXACT_MAXLEN],
        }
    }

    pub fn clear(&mut self) {
        self.mm.clear();
        self.anc.clear();
        self.reach_end = 0;
        self.len = 0;
        self.s[0] = 0;
    }

    pub fn is_full(&self) -> bool {
        self.len >= OPT_EXACT_MAXLEN
    }
}

#[derive(Clone, Copy)]
pub struct OptMap {
    pub mm: MinMaxLen,
    pub anc: OptAnc,
    pub value: i32,
    pub map: [u8; CHAR_MAP_SIZE],
}

impl OptMap {
    pub fn new() -> Self {
        OptMap {
            mm: MinMaxLen::new(),
            anc: OptAnc::new(),
            value: 0,
            map: [0u8; CHAR_MAP_SIZE],
        }
    }

    pub fn clear(&mut self) {
        self.mm.clear();
        self.anc.clear();
        self.value = 0;
        self.map = [0u8; CHAR_MAP_SIZE];
    }
}

#[derive(Clone)]
pub struct OptNode {
    pub len: MinMaxLen,
    pub anc: OptAnc,
    pub sb: OptStr,
    pub sm: OptStr,
    pub spr: OptStr,
    pub map: OptMap,
}

impl OptNode {
    pub fn new() -> Self {
        OptNode {
            len: MinMaxLen::new(),
            anc: OptAnc::new(),
            sb: OptStr::new(),
            sm: OptStr::new(),
            spr: OptStr::new(),
            map: OptMap::new(),
        }
    }

    pub fn clear(&mut self) {
        self.len.clear();
        self.anc.clear();
        self.sb.clear();
        self.sm.clear();
        self.spr.clear();
        self.map.clear();
    }
}

// === Option check macros as functions ===
#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn opton_ignorecase(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_IGNORECASE)
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn opton_extend(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_EXTEND)
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn opton_multiline(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_MULTILINE)
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn opton_singleline(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_SINGLELINE)
}

#[inline]
pub fn opton_find_longest(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_FIND_LONGEST)
}

#[inline]
pub fn opton_find_not_empty(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_FIND_NOT_EMPTY)
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn opton_negate_singleline(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_NEGATE_SINGLELINE)
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn opton_dont_capture_group(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_DONT_CAPTURE_GROUP)
}

#[inline]
pub fn opton_capture_group(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_CAPTURE_GROUP)
}

#[inline]
pub fn opton_notbol(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_NOTBOL)
}

#[inline]
pub fn opton_noteol(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_NOTEOL)
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn opton_posix_region(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_POSIX_REGION)
}

#[inline]
pub fn opton_check_validity_of_string(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_CHECK_VALIDITY_OF_STRING)
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn opton_callback_each_match(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_CALLBACK_EACH_MATCH)
}

#[inline]
pub fn opton_not_begin_string(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_NOT_BEGIN_STRING)
}

#[inline]
pub fn opton_not_end_string(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_NOT_END_STRING)
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn opton_not_begin_position(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_NOT_BEGIN_POSITION)
}

#[inline]
pub fn opton_match_whole_string(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_MATCH_WHOLE_STRING)
}

// === Syntax macros ===
#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mc_esc(syn: &OnigSyntaxType) -> OnigCodePoint {
    syn.meta_char_table.esc
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mc_anychar(syn: &OnigSyntaxType) -> OnigCodePoint {
    syn.meta_char_table.anychar
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mc_anytime(syn: &OnigSyntaxType) -> OnigCodePoint {
    syn.meta_char_table.anytime
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mc_zero_or_one_time(syn: &OnigSyntaxType) -> OnigCodePoint {
    syn.meta_char_table.zero_or_one_time
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mc_one_or_more_time(syn: &OnigSyntaxType) -> OnigCodePoint {
    syn.meta_char_table.one_or_more_time
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mc_anychar_anytime(syn: &OnigSyntaxType) -> OnigCodePoint {
    syn.meta_char_table.anychar_anytime
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn is_mc_esc_code(code: OnigCodePoint, syn: &OnigSyntaxType) -> bool {
    code == mc_esc(syn) && !is_syntax_op2(syn, ONIG_SYN_OP2_INEFFECTIVE_ESCAPE)
}

// === Value helpers ===
#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn digitval(code: OnigCodePoint) -> u32 {
    code - b'0' as u32
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn odigitval(code: OnigCodePoint) -> u32 {
    digitval(code)
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn is_code_word_ascii(code: OnigCodePoint) -> bool {
    code < 128
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn is_code_digit_ascii(code: OnigCodePoint) -> bool {
    code < 128 && (code >= b'0' as u32 && code <= b'9' as u32)
}