rypipe-core 0.6.1

Format-agnostic ingestion framework with Arrow export
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
use std::borrow::Cow;
use std::ops::Range;

use arrow::record_batch::RecordBatch;

use crate::value::Value;
use crate::Result;

// ---------------------------------------------------------------------------
// Chunk-size floor
// ---------------------------------------------------------------------------

/// Minimum chunk size in bytes. Sub-MB chunks collapse throughput due to
/// per-chunk fixed cost (thread dispatch, cache cold start). Measured:
/// 100 MB at par128 (0.78 MB chunks) = 2,265 MB/s vs par16 (6.25 MB) = 3,735.
pub const MIN_CHUNK_BYTES: usize = 2 << 20; // 2 MiB

/// Maximum number of split chunks. Above this, scheduling overhead dominates.
pub const MAX_SPLIT_CHUNKS: usize = 1024;

/// Mode for chunk planning: parallel and streaming have different optima.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SplitMode {
    /// Parallel: peak at 4 MB chunks (measured on 533 MB, 16 cores).
    Parallel,
    /// Streaming: peak at 2 MB chunks (measured with bounded memory).
    Streaming,
}

/// Plan the number of chunks given input size, thread count, and mode.
/// Returns a value in `[threads, MAX_SPLIT_CHUNKS]` with a floor of
/// `min_chunk_bytes` (default [`MIN_CHUNK_BYTES`] via [`plan_chunk_count`]).
pub fn plan_chunk_count_with(
    bytes: usize,
    threads: usize,
    mode: SplitMode,
    min_chunk_bytes: usize,
) -> usize {
    let by_size = bytes / min_chunk_bytes.max(1);
    let cap = match mode {
        SplitMode::Parallel => 16usize.saturating_mul(threads),
        SplitMode::Streaming => 8usize.saturating_mul(threads),
    };
    by_size.min(cap).max(threads).min(MAX_SPLIT_CHUNKS)
}

/// [`plan_chunk_count_with`] using the default [`MIN_CHUNK_BYTES`] floor.
pub fn plan_chunk_count(bytes: usize, threads: usize, mode: SplitMode) -> usize {
    plan_chunk_count_with(bytes, threads, mode, MIN_CHUNK_BYTES)
}

// ---------------------------------------------------------------------------
// SkipRegionFinder: byte ranges where a candidate boundary is invalid
// ---------------------------------------------------------------------------

/// Finds byte ranges (comments, CDATA, quoted fields, string literals) where
/// a candidate record boundary must be rejected.  The engine calls this
/// during split-point discovery to avoid splitting inside comments or strings.
pub trait SkipRegionFinder: Send + Sync {
    /// Openers that start a skip region (e.g. `b"<!--"`, `b"<![CDATA["`).
    fn openers(&self) -> &[&'static [u8]];

    /// The closer for a given opener (e.g. `"-->"` for `"<!--"`).
    fn closer_for(&self, opener: &[u8]) -> &'static [u8];

    /// Maximum backward scan window in bytes.  Default 64 KiB: sufficient
    /// for most XML/CSV comments and JSON string literals.
    fn window(&self) -> usize {
        64 * 1024
    }
}

/// Check whether byte position `at` falls inside a skip region by scanning
/// backward up to `finder.window()` bytes, looking for an unclosed opener.
///
/// Returns `false` immediately when the file contains none of the openers;
/// check that once per chunk, not per candidate.
pub fn in_skip_region(bytes: &[u8], at: usize, finder: &dyn SkipRegionFinder) -> bool {
    if at > bytes.len() {
        return false;
    }
    let openers = finder.openers();
    if openers.is_empty() {
        return false;
    }
    let scan_start = at.saturating_sub(finder.window());
    let scan = &bytes[scan_start..at];
    for opener in openers {
        let closer = finder.closer_for(opener);
        // Use memchr::memmem::find directly (no Finder::new preprocessing).
        let mut search = 0;
        while let Some(rel) = memchr::memmem::find(&scan[search..], opener) {
            let open_pos = scan_start + search + rel;
            // Check if there's a closer between the opener and `at`.
            let closer_start = open_pos + opener.len();
            if closer_start >= at {
                // Opener extends past `at`; treat as unclosed (inside skip region).
                return true;
            }
            let between = &bytes[closer_start..at];
            if memchr::memmem::find(between, closer).is_none() {
                // Unclosed opener; `at` is inside this skip region.
                return true;
            }
            search += rel + 1;
        }
    }
    false
}

// ---------------------------------------------------------------------------
// Splitter trait with default
// ---------------------------------------------------------------------------

/// How records are separated in the input.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RecordBoundary {
    /// Split on every newline (default). Each `\n` is a record boundary.
    #[default]
    Line,
    /// Split on blank lines. Records span multiple lines; a blank line
    /// (`\n\n`) separates records.
    BlankLine,
}

/// Format-specific splitter: decides where it is safe to divide an input byte
/// stream into independent chunks.
///
/// The only required method is `next_record_start`; adapters provide the
/// record boundary logic, and the engine handles chunk planning, skip-region
/// rejection, and deduplication.
///
/// For multi-line formats, implement the declarative methods
/// ([`record_boundary`](Self::record_boundary),
/// [`continuation_char`](Self::continuation_char),
/// [`comment_prefixes`](Self::comment_prefixes)) and call
/// [`find_next_record_boundary`] from your `next_record_start`:
///
/// ```rust
/// use rypipe_core::{find_next_record_boundary, RecordBoundary, Splitter};
/// struct Lines;
/// impl Splitter for Lines {
///     fn next_record_start(&self, bytes: &[u8], from: usize) -> Option<usize> {
///         find_next_record_boundary(bytes, from, self.continuation_char(), self.comment_prefixes(), self.record_boundary() == RecordBoundary::BlankLine)
///     }
///     fn estimate_bytes_per_row(&self, sample: &[u8]) -> usize { sample.len().max(1) }
/// }
/// assert_eq!(Lines.next_record_start(b"one\ntwo\n", 0), Some(4));
/// ```
pub trait Splitter: Send + Sync {
    /// Return the next record boundary at or after `from`.  Must return a
    /// position where a record starts, or `None` if no more records exist.
    fn next_record_start(&self, bytes: &[u8], from: usize) -> Option<usize>;

    /// Estimate the average bytes per record from a sample of the input.
    fn estimate_bytes_per_row(&self, sample: &[u8]) -> usize;

    /// How records are separated. Default: [`RecordBoundary::Line`] (every
    /// newline is a boundary). Override to [`RecordBoundary::BlankLine`] for
    /// multi-line formats where blank lines separate records.
    fn record_boundary(&self) -> RecordBoundary {
        RecordBoundary::Line
    }

    /// Character that continues a record across lines (e.g. `b'\\'` for
    /// properties files). When set, newlines preceded by this character are
    /// NOT record boundaries. Default: `None` (no continuations).
    fn continuation_char(&self) -> Option<u8> {
        None
    }

    /// Line prefixes to skip (e.g. `&[b"#", b"!"]` for properties files).
    /// Lines starting with any of these are ignored during splitting.
    /// Default: empty (no comments).
    fn comment_prefixes(&self) -> &[&[u8]] {
        &[]
    }

    /// Optional: byte ranges where a candidate boundary must be rejected.
    /// See `in_skip_region`.
    fn skip_regions(&self) -> Option<&dyn SkipRegionFinder> {
        None
    }

    /// Find split points.  **Do not override** without a measured reason.
    ///
    /// Returns a sorted list of byte offsets where it is safe to split the
    /// input into independent chunks. The return value must satisfy:
    /// - Sorted ascending, no duplicates.
    /// - First element is `0`, last element is `bytes.len()`.
    /// - All values are `<= bytes.len()`.
    ///
    /// Default implementation:
    /// 1. Nominal offsets at `bytes.len() * i / n` for `i in 1..n`.
    /// 2. Scan each nominal offset with `next_record_start`.
    /// 3. Reject candidates inside skip regions via `in_skip_region`.
    /// 4. Dedup, sort, prepend 0.
    /// 5. Apply chunk floor via `plan_chunk_count`.
    ///
    /// This is the default-floor entry point. Adapters that override it keep
    /// working; engines call [`Splitter::find_split_points_with`] instead, and
    /// that defers to this override at the default floor.
    fn find_split_points(&self, bytes: &[u8], max_chunks: usize) -> Vec<usize> {
        default_find_split_points(self, bytes, max_chunks, MIN_CHUNK_BYTES)
    }

    /// Find split points with an explicit chunk-size floor.
    ///
    /// The floor is opt-in: lowering it yields more, smaller chunks (better
    /// load balancing on many or small cores, at more scheduling overhead);
    /// raising it yields fewer, larger chunks. Default is [`MIN_CHUNK_BYTES`].
    ///
    /// At the default floor this calls [`Splitter::find_split_points`], so an
    /// adapter's override is honored; a non-default floor uses the engine's
    /// default planning (override `find_split_points_with` to customize it).
    fn find_split_points_with(
        &self,
        bytes: &[u8],
        max_chunks: usize,
        min_chunk_bytes: usize,
    ) -> Vec<usize> {
        if min_chunk_bytes == MIN_CHUNK_BYTES {
            return self.find_split_points(bytes, max_chunks);
        }
        default_find_split_points(self, bytes, max_chunks, min_chunk_bytes)
    }
}

/// The engine's default chunk planning, shared by the `Splitter` methods.
fn default_find_split_points<S: Splitter + ?Sized>(
    splitter: &S,
    bytes: &[u8],
    max_chunks: usize,
    min_chunk_bytes: usize,
) -> Vec<usize> {
    if max_chunks <= 1 || bytes.is_empty() {
        return vec![0, bytes.len()];
    }
    let n = plan_chunk_count_with(
        bytes.len(),
        max_chunks,
        SplitMode::Parallel,
        min_chunk_bytes,
    );
    let skip = splitter.skip_regions();
    // Planning must not start a global worker pool for bounded readers.
    let mut points: Vec<usize> = (1..n)
        .filter_map(|i| {
            let approx = bytes.len() / n * i;
            let pos = splitter.next_record_start(bytes, approx)?;
            // Reject candidates inside skip regions.
            if skip.is_some_and(|finder| in_skip_region(bytes, pos, finder)) {
                return None;
            }
            Some(pos)
        })
        .collect();

    points.sort_unstable();
    points.dedup();
    // Drop candidates at 0: the prepend below already supplies the
    // leading split point, and keeping them would duplicate it (this
    // happens when bytes.len() < n, where bytes.len() / n == 0 puts
    // every nominal offset at 0).
    points.retain(|&p| p > 0);
    points.insert(0, 0);
    if *points.last().unwrap_or(&0) != bytes.len() {
        points.push(bytes.len());
    }
    points
}

// ---------------------------------------------------------------------------
// Declarative splitting helpers
// ---------------------------------------------------------------------------

/// Check whether the newline at `pos` is preceded by a continuation character.
///
/// Used by Splitters that need to skip continued newlines. For example, in
/// properties files, `key = value \` continues on the next line: the `\n`
/// after `\` is NOT a record boundary.
///
/// ```rust
/// use rypipe_core::is_continued_newline;
/// assert!(is_continued_newline(b"key=value\\\nnext\n", 10));
/// ```
#[inline]
pub fn is_continued_newline(bytes: &[u8], pos: usize) -> bool {
    if pos == 0 || bytes.get(pos) != Some(&b'\n') {
        return false;
    }
    let mut run = 0;
    let mut cursor = pos;
    if bytes[cursor - 1] == b'\r' {
        cursor -= 1;
    }
    while cursor > 0 && bytes[cursor - 1] == b'\\' {
        run += 1;
        cursor -= 1;
    }
    run % 2 == 1
}

/// Scan forward from `from` to find the next record boundary.
///
/// This is the declarative counterpart to manual byte scanning. It handles:
/// - **Continuations**: skips `\n` preceded by `continuation` (e.g. `b'\\'`)
/// - **Comments**: skips lines starting with any prefix in `comment_prefixes`
/// - **Blank-line mode**: splits after an empty LF or CRLF line
///
/// Returns the byte position after the boundary newline, or `None` if no
/// more boundaries exist.
///
/// # Example
///
/// ```rust
/// use rypipe_core::find_next_record_boundary;
/// let input = b"# comment\nfirst\nsecond\n";
/// assert_eq!(find_next_record_boundary(input, 0, None, &[b"#"], false), Some(16));
/// ```
#[inline]
pub fn find_next_record_boundary(
    bytes: &[u8],
    from: usize,
    continuation: Option<u8>,
    comment_prefixes: &[&[u8]],
    blank_line_mode: bool,
) -> Option<usize> {
    if continuation.is_none() && comment_prefixes.is_empty() && !blank_line_mode {
        return memchr::memchr(b'\n', bytes.get(from..)?).map(|offset| from + offset + 1);
    }
    let mut pos = from;
    while pos < bytes.len() {
        let rel = memchr::memchr(b'\n', &bytes[pos..])?;
        let nl_pos = pos + rel;

        // Skip continued newlines (preceded by continuation character)
        let continued = |newline: usize| {
            continuation.is_some_and(|character| {
                let end = if newline > 0 && bytes[newline - 1] == b'\r' {
                    newline - 1
                } else {
                    newline
                };
                if character == b'\\' {
                    is_continued_newline(bytes, newline)
                } else {
                    end > 0 && bytes[end - 1] == character
                }
            })
        };
        if continued(nl_pos) {
            pos = nl_pos + 1;
            continue;
        }

        if !blank_line_mode && comment_prefixes.is_empty() {
            return Some(nl_pos + 1);
        }

        if blank_line_mode {
            let end = nl_pos - usize::from(nl_pos > 0 && bytes[nl_pos - 1] == b'\r');
            if end == 0 || bytes[end - 1] != b'\n' {
                pos = nl_pos + 1;
                continue;
            }
            if comment_prefixes.is_empty() && !continued(end - 1) {
                return Some(nl_pos + 1);
            }
        }

        // Compute line start for comment check
        let line_start = memchr::memrchr(b'\n', &bytes[..nl_pos]).map_or(0, |p| p + 1);

        // Skip comment lines
        if !comment_prefixes.is_empty() {
            let line_bytes = &bytes[line_start..nl_pos];
            let is_comment = comment_prefixes
                .iter()
                .any(|prefix| line_bytes.starts_with(prefix));
            if is_comment {
                pos = nl_pos + 1;
                continue;
            }
        }

        // Blank-line mode: split on empty lines
        if blank_line_mode {
            let line = &bytes[line_start..nl_pos];
            if line_start > 0 && (line.is_empty() || line == b"\r") && !continued(line_start - 1) {
                let previous_start =
                    memchr::memrchr(b'\n', &bytes[..line_start - 1]).map_or(0, |p| p + 1);
                if !comment_prefixes
                    .iter()
                    .any(|prefix| bytes[previous_start..line_start - 1].starts_with(prefix))
                {
                    return Some(nl_pos + 1);
                }
            }
            pos = nl_pos + 1;
            continue;
        }

        // Line mode: every newline is a boundary
        return Some(nl_pos + 1);
    }
    None
}

/// Format-specific parser: turns a byte chunk into field/value events sent to
/// a `ColumnarSink`.
pub trait RecordParser: Send + Sync {
    /// Validate that the whole byte slice is well-formed for this format.
    fn validate(&self, bytes: &[u8]) -> Result<()>;

    /// Parse one chunk and feed all row events into `sink` (object-safe, virtual).
    fn parse_chunk(&self, bytes: &[u8], sink: &mut dyn ColumnarSink) -> Result<()>;

    /// Parse one chunk generically (monomorphized, inlinable).
    ///
    /// Default impl delegates to `parse_chunk` (object-safe) for adapters that
    /// have not yet migrated. Adapters that implement this directly get
    /// devirtualized `sink` calls and cross-crate inlining.
    #[inline]
    fn parse_chunk_generic<S: ColumnarSink>(&self, bytes: &[u8], sink: &mut S) -> Result<()>
    where
        Self: Sized,
    {
        // Default impl delegates to the object-safe path. Adapters that override
        // this method get devirtualized sink calls and cross-crate inlining.
        self.parse_chunk(bytes, sink as &mut dyn ColumnarSink)
    }
}

/// Sink for decoder events.  The decoder calls `begin_row` / `put_field` /
/// `end_row` for each record.
///
/// Implementations must be `Send + Sync` when used with the parallel or
/// parallel_streaming executors. `TableBuilder` satisfies this.
pub trait ColumnarSink {
    /// Begin a new row. Must be paired with exactly one `end_row` per row.
    fn begin_row(&mut self);
    fn put_field(&mut self, name: &str, value: Value<'_>);

    /// Push a complete row.
    ///
    /// The default preserves event-oriented semantics. Sinks may override this
    /// to optimize row handling while preserving filtering and duplicate-field
    /// behavior.
    #[inline]
    fn put_row(&mut self, fields: &[(&str, Value<'_>)]) {
        for (name, value) in fields {
            self.put_field(name, value.clone());
        }
    }

    /// Resolve a valid raw name without allocating a UTF-8 `String`.
    #[inline]
    fn resolve_raw<'a>(&'a self, raw_name: &'a [u8]) -> Option<&'a str> {
        std::str::from_utf8(raw_name)
            .ok()
            .and_then(|name| self.resolve(name))
    }

    /// Push a value for a field whose name is still in its raw byte form.
    #[inline]
    fn resolve_and_put_raw(&mut self, raw_name: &[u8], value: Value<'_>) {
        if let Ok(name) = std::str::from_utf8(raw_name) {
            self.resolve_and_put(name, value);
        }
    }

    /// End the current row. Must be paired with exactly one `begin_row` per row.
    fn end_row(&mut self);

    /// Return `false` to signal that the engine will drop this field.
    #[inline]
    fn wants(&self, _name: &str) -> bool {
        true
    }

    /// Resolve a raw field name to its output column name, or `None` if dropped.
    /// Default keeps the name as-is. Adapters that do expensive extraction can
    /// call this once and then `put_field_resolved` to avoid a second
    /// `resolve_field` inside `put_field`.
    #[inline]
    fn resolve<'a>(&'a self, name: &'a str) -> Option<&'a str> {
        Some(name)
    }

    /// Push a field that has already been resolved via `resolve`.
    /// Default delegates to `put_field` (which will resolve again). Overrides
    /// should bypass the rename/drop lookup.
    #[inline]
    fn put_field_resolved(&mut self, resolved_name: &str, value: Value<'_>) {
        self.put_field(resolved_name, value);
    }

    /// Push a value directly to a known slot index, bypassing all name
    /// resolution, hash lookups, and attribute scanning.  Used by adapters
    /// that have verified the field identity via `expect_slot` + memcmp.
    ///
    /// Default: discards the value. Engines MUST override this to push
    /// directly to columns by slot index; the default silently drops data.
    #[inline]
    fn put_field_at(&mut self, _slot: u32, value: Value<'_>) {
        let _ = value;
    }

    /// Push a known-`&str` field into a known slot, bypassing the `Value`
    /// round trip. Default forwards to `put_field_at`; sinks that store strings
    /// directly (e.g. `TableBuilder`) override it for the hot path.
    #[inline]
    fn put_str_at(&mut self, slot: u32, value: &str) {
        self.put_field_at(slot, Value::Str(Cow::Borrowed(value)));
    }

    /// Resolve a field name and push it in one call, avoiding the double
    /// `resolve_field` that `wants` + `put_field` would perform.
    /// Default: resolve then put_field_resolved (with owned clone to satisfy
    /// the borrow checker). Overrides should avoid the allocation.
    #[inline]
    fn resolve_and_put(&mut self, name: &str, value: Value<'_>) {
        if let Some(resolved) = self.resolve(name) {
            let owned = resolved.to_owned();
            self.put_field_resolved(&owned, value);
        }
    }

    /// Whether this sink needs decoded values from the parser.
    ///
    /// Return `false` for locate-only sinks that walk rows and resolve field
    /// names but skip value extraction entirely.  The parser can use this to
    /// bypass expensive text extraction (e.g. `raw_text_until` in XML scanners).
    #[inline]
    fn needs_value(&self) -> bool {
        true
    }

    /// Whether this sink needs field-name resolution (`wants` + `resolve`).
    ///
    /// Return `false` for traversal-only sinks that walk rows and find field
    /// extents but don't need to resolve names or check `wants`.  When false,
    /// the parser skips `wants()` and `resolve()` calls entirely; it only
    /// locates the byte extents of each field within a row.
    ///
    /// **Note:** this method is primarily for benchmarking/profiling harnesses.
    /// A sink returning `false` may receive `put_field` calls with unresolved
    /// names, or none at all, depending on the adapter.  Consider this
    /// experimental until a non-benchmark consumer exists.
    #[doc(hidden)]
    #[inline]
    fn needs_resolve(&self) -> bool {
        true
    }

    /// Whether the current row has been rejected by the filter and the scanner
    /// should skip the remainder of the row. Used for predicate-first
    /// deferred materialization: once `Fail`, the scanner can byte-jump to
    /// `</Details>` without further field scanning. Default false.
    #[inline]
    fn row_rejected(&self) -> bool {
        false
    }

    /// Return true to abort parsing early. Parsers should check this between
    /// records. Bounded single-pass sinks use it to stop promptly when the
    /// consumer has gone away (e.g. a dropped streaming iterator), instead of
    /// finishing the whole input. Default false (never stop early).
    #[inline]
    fn should_stop(&self) -> bool {
        false
    }

    /// Whether every wanted column for the current row already has a value.
    /// The adapter can byte-jump to the row close tag when this returns true,
    /// skipping remaining fields.  Composes with `row_rejected` (a row can
    /// be satisfied OR rejected, both short-circuit).
    ///
    /// Default: false (never short-circuit).
    #[inline]
    fn row_satisfied(&self) -> bool {
        false
    }

    /// Bitmask of columns that the projection wants.  Bit `i` is set iff
    /// column `i` is in the output schema.  The adapter can test membership
    /// with `(wanted_mask >> slot) & 1 == 1` instead of a virtual call per
    /// field.  Returns empty mask (all zeros) when no projection is active.
    #[inline]
    fn wanted_mask(&self) -> u64 {
        0
    }

    /// After the layout is learned, the expected (slot, raw name bytes) at
    /// this ordinal position in the record.  The adapter can compare the
    /// raw bytes in-place (one memcmp) instead of running the full
    /// attribute scan → UTF-8 decode → hash → lookup path.
    ///
    /// Return `None` to fall back to the generic path.  Default: `None`.
    #[inline]
    fn expect_slot(&self, _ordinal: u32) -> Option<(u32, &[u8])> {
        None
    }

    /// Adapter reports the slot it resolved for `ordinal` so the engine
    /// can cache it for subsequent rows.  Called after the adapter resolves
    /// a field via the generic path (wants + resolve + put_field_resolved).
    #[inline]
    fn record_slot(&mut self, _ordinal: u32, _slot: u32, _raw_name: &[u8]) {}

    /// Adapter reports that the layout expected at `ordinal` did not match.
    /// The engine should invalidate its cached expectation and fall back to
    /// generic resolution for subsequent rows.
    #[inline]
    fn layout_broken(&mut self, _ordinal: u32) {}

    /// Reset the ordinal counter for child-element tracking.  Called after
    /// row-tag attributes are emitted so child ordinals start at 0.
    #[inline]
    fn reset_child_ordinal(&mut self) {}

    /// Finalize the sink into an Arrow `RecordBatch`.
    fn finish(&mut self) -> Result<RecordBatch>;
}

/// Convert split-point offsets returned by a `Splitter` into non-empty
/// `Range<usize>` chunks.
pub fn split_points_to_ranges(points: &[usize], len: usize) -> Vec<Range<usize>> {
    if points.len() < 2 {
        return std::iter::once(0..len).collect();
    }
    points
        .windows(2)
        .filter_map(|w| {
            let (start, end) = (w[0], w[1]);
            if start < end {
                Some(start..end)
            } else {
                None
            }
        })
        .collect()
}

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

    /// Records start at every multiple of 4, including 0.
    struct FixedWidthSplitter;

    impl Splitter for FixedWidthSplitter {
        fn next_record_start(&self, bytes: &[u8], from: usize) -> Option<usize> {
            (from..bytes.len()).find(|&p| p % 4 == 0)
        }

        fn estimate_bytes_per_row(&self, _sample: &[u8]) -> usize {
            4
        }
    }

    #[test]
    fn find_split_points_no_duplicate_leading_zero() {
        // Input shorter than the planned chunk count: bytes.len() / n == 0
        // puts every nominal offset at 0, so without the guard the prepended
        // 0 duplicates the candidate at 0.
        let bytes = vec![0u8; 8];
        let splitter = FixedWidthSplitter;
        for max_chunks in [2, 8, 64, 1024] {
            let points = splitter.find_split_points(&bytes, max_chunks);
            assert_eq!(points.first(), Some(&0), "must start at 0");
            assert_eq!(points.last(), Some(&bytes.len()), "must end at len");
            assert!(
                points.windows(2).all(|w| w[0] < w[1]),
                "duplicate or unsorted points for max_chunks={max_chunks}: {points:?}"
            );
        }
    }
}

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

    /// A splitter that overrides the documented entry point with a sentinel.
    struct FixedSplitter;
    impl Splitter for FixedSplitter {
        fn next_record_start(&self, bytes: &[u8], from: usize) -> Option<usize> {
            (from..bytes.len())
                .find(|&p| bytes[p] == b'\n')
                .map(|p| p + 1)
        }
        fn estimate_bytes_per_row(&self, _sample: &[u8]) -> usize {
            4
        }
        fn find_split_points(&self, _bytes: &[u8], _max_chunks: usize) -> Vec<usize> {
            vec![0, 7]
        }
    }

    #[test]
    fn adapter_override_is_honored_at_the_default_floor() {
        // Engines call find_split_points_with; at the default floor it must
        // defer to an adapter's find_split_points override.
        assert_eq!(
            FixedSplitter.find_split_points_with(b"ignored", 8, MIN_CHUNK_BYTES),
            vec![0, 7]
        );
    }

    #[test]
    fn a_lower_floor_yields_more_chunks() {
        let bytes = 8 << 20; // 8 MiB
        let default = plan_chunk_count_with(bytes, 4, SplitMode::Parallel, MIN_CHUNK_BYTES);
        let small = plan_chunk_count_with(bytes, 4, SplitMode::Parallel, 256 * 1024);
        assert!(small > default, "default={default} small={small}");
    }
}