excelreader 6.0.0

Read and write Excel/CSV workbooks via ExcelReader's native ABI (schema-driven typed parse and write).
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
907
908
909
use crate::{
    Date, Error, OpenOptions, Time, Timestamp, XlColumn, XlColumnSpec, XlInferredSchema, XlTable,
    XlWorkbook, XL_BUFFER_TOO_SMALL, XL_EOF, XL_ERROR, XL_FORMAT_AUTO, XL_OK, XL_T_BOOL, XL_T_DATE,
    XL_T_F64, XL_T_I64, XL_T_STRING, XL_T_TIME, XL_T_TIMESTAMP,
};
use std::marker::PhantomData;

pub(crate) fn last_error(code: i32) -> Error {
    unsafe {
        let mut len: i32 = 0;
        let ptr = crate::xl_last_error_ptr(&mut len);
        let message = if ptr.is_null() || len <= 0 {
            "unknown error".to_string()
        } else {
            let bytes = std::slice::from_raw_parts(ptr, len as usize);
            String::from_utf8_lossy(bytes).into_owned()
        };
        Error::from_status(code, message)
    }
}

pub(crate) fn check(code: i32) -> Result<(), Error> {
    if code == XL_OK {
        Ok(())
    } else {
        Err(last_error(code))
    }
}

/// Copies a native `XlBuffer` into an owned `Vec<u8>` and releases the native allocation via
/// `xl_free_buffer` - shared by `writer::write_columns_to_memory`/`write_sheet_to_memory` and
/// `writer_handle::WriterHandle::bytes`, the two places `xl_write_typed_to_memory`/
/// `xl_write_handle_bytes` hand back an owned buffer. `buffer.data` may be null (an empty result),
/// which `from_raw_parts` cannot take - `slice::from_raw_parts` requires a non-null, well-aligned
/// pointer even for a zero-length slice.
pub(crate) fn buffer_to_vec(mut buffer: crate::XlBuffer) -> Vec<u8> {
    let bytes = if buffer.data.is_null() || buffer.len <= 0 {
        Vec::new()
    } else {
        unsafe { std::slice::from_raw_parts(buffer.data, buffer.len as usize).to_vec() }
    };
    unsafe {
        crate::xl_free_buffer(&mut buffer);
    }
    bytes
}

/// Verifies the loaded shared library speaks the ABI revision this crate was compiled against.
///
/// The native binary is resolved at build time from a GitHub release asset (or from
/// `EXCELREADER_NATIVE_LIB_DIR`), so it is entirely possible to end up linking a library built from
/// a different ABI revision than the one this crate's `#[repr(C)]` structs mirror. Proceeding past a
/// mismatch would mean reading native memory through the wrong layout, so every constructor calls
/// this first.
///
/// The result is cached: it cannot change for the lifetime of the process, and every
/// `Workbook::open` would otherwise pay an FFI call for it.
pub(crate) fn check_abi_version() -> Result<(), Error> {
    use std::sync::OnceLock;
    static CHECKED: OnceLock<Result<(), Error>> = OnceLock::new();

    CHECKED
        .get_or_init(|| {
            let loaded = unsafe { crate::xl_abi_version() };
            if loaded == crate::XL_ABI_VERSION {
                warm_up();
                Ok(())
            } else {
                Err(Error::from_status(
                    XL_ERROR,
                    format!(
                        "ExcelReader native library reports ABI version {loaded}, but this crate \
                         was built against {}. Update the crate and the native library together.",
                        crate::XL_ABI_VERSION
                    ),
                ))
            }
        })
        .clone()
}

/// Runs one small read and one small aggregation, so the native runtime finishes starting up on a
/// single thread.
///
/// Several threads whose FIRST call into the library lands in the runtime's class-constructor
/// machinery at the same moment can crash it: a thread comes back from a spin in `Thread.Yield` on
/// a corrupted return address, which ends the process with no message (SIGABRT on Linux, SIGSEGV on
/// macOS). It is not this crate's bug - a plain C host doing the same thing crashes too, just far
/// less often - but this crate makes it likely, because a Rust test binary calls in from a fresh
/// thread per test. [`check_abi_version`]'s `OnceLock` already serializes the first call, so doing
/// the heavy initialization here means later threads find the constructors already run.
///
/// Failures are ignored on purpose: this is a warm-up, and a real call will report the same problem
/// properly.
fn warm_up() {
    const CSV: &[u8] = b"a,b\n1,2\n3,4\n";

    let mut handle: *mut XlWorkbook = std::ptr::null_mut();
    let status = unsafe {
        crate::xl_open_memory(
            CSV.as_ptr(),
            CSV.len() as i32,
            crate::XL_FORMAT_CSV,
            std::ptr::null(),
            &mut handle,
        )
    };
    if status == XL_OK && !handle.is_null() {
        unsafe { crate::xl_close(handle) };
    }

    struct CountRows(i64);
    impl crate::CsvAccumulator for CountRows {
        fn accumulate(&mut self, _row: crate::RowRef<'_>) -> Result<(), i32> {
            self.0 += 1;
            Ok(())
        }
        fn combine(&mut self, other: &mut Self) -> Result<(), i32> {
            self.0 += other.0;
            Ok(())
        }
    }

    let options = crate::CsvParallelOptions {
        degree_of_parallelism: 2,
        ..crate::CsvParallelOptions::default()
    };
    let _ = crate::aggregate::aggregate_csv_memory_unchecked(CSV, || CountRows(0), &options);
}

/// An open workbook. Safe to share between threads: every read goes through a [`Sheet`] and opens
/// its own cursor, so reads on one workbook never disturb one another.
pub struct Workbook {
    handle: *mut XlWorkbook,
}

// SAFETY: ABI v6 documents the workbook handle as usable from several threads at once. The only
// state behind it is immutable after open; each read owns its enumerator.
unsafe impl Send for Workbook {}
unsafe impl Sync for Workbook {}

impl Workbook {
    /// Opens `path`, sniffing the format and using every library default.
    ///
    /// Sniffing does NOT detect CSV - open one with [`open_with`](Self::open_with) and
    /// [`XL_FORMAT_CSV`](crate::XL_FORMAT_CSV).
    pub fn open(path: &str) -> Result<Workbook, Error> {
        Self::open_with(path, XL_FORMAT_AUTO, None)
    }

    /// Opens `path` with an explicit format and optional [`OpenOptions`].
    pub fn open_with(
        path: &str,
        format: i32,
        options: Option<&OpenOptions>,
    ) -> Result<Workbook, Error> {
        check_abi_version()?;
        let raw = options.map(OpenOptions::to_raw);
        let raw_ptr = raw
            .as_ref()
            .map_or(std::ptr::null(), crate::options::OpenOptionsRaw::as_ptr);
        let mut handle: *mut XlWorkbook = std::ptr::null_mut();
        let status = unsafe {
            crate::xl_open_file(
                path.as_ptr(),
                path.len() as i32,
                format,
                raw_ptr,
                &mut handle,
            )
        };
        check(status)?;
        Ok(Workbook { handle })
    }

    /// In-memory equivalent of [`open_with`](Self::open_with): `data` is copied by the native
    /// library, so it need not outlive this call.
    pub fn open_memory(
        data: &[u8],
        format: i32,
        options: Option<&OpenOptions>,
    ) -> Result<Workbook, Error> {
        check_abi_version()?;
        let raw = options.map(OpenOptions::to_raw);
        let raw_ptr = raw
            .as_ref()
            .map_or(std::ptr::null(), crate::options::OpenOptionsRaw::as_ptr);
        let mut handle: *mut XlWorkbook = std::ptr::null_mut();
        let status = unsafe {
            crate::xl_open_memory(
                data.as_ptr(),
                data.len() as i32,
                format,
                raw_ptr,
                &mut handle,
            )
        };
        check(status)?;
        Ok(Workbook { handle })
    }

    /// Number of sheets in the workbook.
    pub fn sheet_count(&self) -> Result<i32, Error> {
        let mut count: i32 = 0;
        check(unsafe { crate::xl_sheet_count(self.handle, &mut count) })?;
        Ok(count)
    }

    /// Name of the sheet at `index`.
    pub fn sheet_name_at(&self, index: i32) -> Result<String, Error> {
        self.fill_string(|handle, buffer, capacity, out_len| unsafe {
            crate::xl_sheet_name_at(handle, index, buffer, capacity, out_len)
        })
    }

    /// Every sheet name, in workbook order.
    pub fn sheet_names(&self) -> Result<Vec<String>, Error> {
        (0..self.sheet_count()?)
            .map(|index| self.sheet_name_at(index))
            .collect()
    }

    /// Whether the workbook uses the 1904 date system - needed to interpret raw Excel serial dates.
    pub fn is_date1904(&self) -> Result<bool, Error> {
        let mut flag: i32 = 0;
        check(unsafe { crate::xl_is_date1904(self.handle, &mut flag) })?;
        Ok(flag != 0)
    }

    /// The sheet at `index`. An index outside the workbook is an error here, not at the first read.
    pub fn sheet(&self, index: i32) -> Result<Sheet<'_>, Error> {
        let mut visibility: i32 = 0;
        check(unsafe { crate::xl_sheet_visibility_at(self.handle, index, &mut visibility) })?;
        Ok(Sheet { workbook: self, index })
    }

    /// Every sheet, in workbook order. Opens nothing.
    pub fn sheets(&self) -> Result<Vec<Sheet<'_>>, Error> {
        Ok((0..self.sheet_count()?)
            .map(|index| Sheet { workbook: self, index })
            .collect())
    }

    /// The sheet called `name`, compared without regard to case. `Ok(None)` when no sheet matches.
    pub fn sheet_by_name(&self, name: &str) -> Result<Option<Sheet<'_>>, Error> {
        let mut index: i32 = -1;
        check(unsafe {
            crate::xl_sheet_index(self.handle, name.as_ptr(), name.len() as i32, &mut index)
        })?;
        Ok((index >= 0).then_some(Sheet { workbook: self, index }))
    }

    /// Shared two-pass buffer dance for the `xl_*` functions that write a UTF-8 name into a caller
    /// buffer and report the required capacity through `XL_BUFFER_TOO_SMALL`.
    fn fill_string(
        &self,
        call: impl Fn(*mut XlWorkbook, *mut u8, i32, *mut i32) -> i32,
    ) -> Result<String, Error> {
        let mut buffer = [0u8; 128];
        let mut len: i32 = 0;
        let mut status = call(
            self.handle,
            buffer.as_mut_ptr(),
            buffer.len() as i32,
            &mut len,
        );
        if status != XL_BUFFER_TOO_SMALL {
            check(status)?;
            let buffer_slice = &buffer[..len.max(0) as usize];
            return str::from_utf8(buffer_slice)
                .map(|s| s.to_string())
                .map_err(|e| {
                    Error::from_status(
                        XL_ERROR,
                        format!("native library returned a non-UTF-8 name: {e}"),
                    )
                });
        }
        let mut vec_buffer = vec![0u8; len.max(0) as usize];
        status = call(
            self.handle,
            vec_buffer.as_mut_ptr(),
            vec_buffer.len() as i32,
            &mut len,
        );
        check(status)?;
        vec_buffer.truncate(len.max(0) as usize);
        String::from_utf8(vec_buffer).map_err(|e| {
            Error::from_status(
                XL_ERROR,
                format!("native library returned a non-UTF-8 name: {e}"),
            )
        })
    }
}

/// How a sheet is shown in the application's tab bar.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SheetVisibility {
    Visible,
    Hidden,
    VeryHidden,
}

/// One sheet of a [`Workbook`]: the workbook and an index. Holds no native resource, so it is
/// `Copy` and free to pass to another thread; each read method opens what it needs.
#[derive(Clone, Copy)]
pub struct Sheet<'w> {
    workbook: &'w Workbook,
    index: i32,
}

impl<'w> Sheet<'w> {
    /// Zero-based position in the workbook.
    #[must_use]
    pub fn index(&self) -> i32 {
        self.index
    }

    /// The sheet's name.
    pub fn name(&self) -> Result<String, Error> {
        self.workbook.sheet_name_at(self.index)
    }

    /// Whether the sheet is visible, hidden or very hidden. An error if the native side reports a
    /// value this crate does not know.
    pub fn visibility(&self) -> Result<SheetVisibility, Error> {
        let mut raw: i32 = 0;
        check(unsafe {
            crate::xl_sheet_visibility_at(self.workbook.handle, self.index, &mut raw)
        })?;
        match raw {
            crate::XL_SHEET_VISIBLE => Ok(SheetVisibility::Visible),
            crate::XL_SHEET_HIDDEN => Ok(SheetVisibility::Hidden),
            crate::XL_SHEET_VERY_HIDDEN => Ok(SheetVisibility::VeryHidden),
            other => Err(Error::from_status(
                XL_ERROR,
                format!("native library returned an unknown sheet visibility {other}"),
            )),
        }
    }

    /// A row-at-a-time reader over this sheet, from its first row. Each call opens an independent
    /// cursor, so several may be alive at once, on this thread or on others.
    pub fn rows(&self) -> Result<crate::rows::RowCursor<'w>, Error> {
        crate::rows::RowCursor::open(self.workbook.handle, self.index)
    }

    /// Every row of this sheet in one native call, avoiding a round-trip per row.
    pub fn read_all_decoded(&self) -> Result<crate::rows::DecodedRows, Error> {
        let cursor = self.rows()?;
        let mut raw = crate::XlRowsDecoded { row_count: 0, rows: std::ptr::null_mut() };
        check(unsafe { crate::xl_rows_read_all_decoded(cursor.raw(), &mut raw) })?;
        Ok(crate::rows::DecodedRows::new(raw))
    }

    /// Every row of this sheet, read in one native call into a buffer this type owns outright.
    /// Prefer this over [`read_all_decoded`](Self::read_all_decoded) unless something specifically
    /// needs the decoded-array shape.
    pub fn read_all_blob(&self) -> Result<crate::rows::AllRows, Error> {
        let cursor = self.rows()?;
        crate::rows::AllRows::read(cursor.raw())
    }

    /// [`parse_sheet`] delivered a batch at a time. `batch_size` is rows per batch: 0 unbounded,
    /// negative an error. The header row is consumed once, here, not re-read per batch.
    pub fn typed_chunks<T: ExcelMapper>(
        &self,
        header_row: i32,
        batch_size: i64,
    ) -> Result<TypedChunks<'w, T>, Error> {
        let arena = build_specs::<T>();
        let mut reader: *mut crate::XlTypedReader = std::ptr::null_mut();
        check(unsafe {
            crate::xl_typed_reader_open(
                self.workbook.handle,
                self.index,
                arena.specs.as_ptr(),
                arena.specs.len() as i32,
                header_row,
                batch_size,
                &mut reader,
            )
        })?;
        Ok(TypedChunks {
            reader,
            bindings: arena.bindings,
            done: false,
            _workbook: PhantomData,
        })
    }

    /// Guesses a [`parse_sheet`] schema by sampling this sheet.
    ///
    /// `header_row` has the same meaning as in [`parse_sheet`] (0 = no header); `sample_size`
    /// bounds how many rows after the header are inspected. This is a guess over a sample, not a
    /// guarantee - always check it fits before trusting it against the full sheet.
    pub fn infer_schema(
        &self,
        header_row: i32,
        sample_size: i32,
    ) -> Result<Vec<InferredColumn>, Error> {
        self.infer_schema_flags(header_row, sample_size, 0)
    }

    /// [`infer_schema`](Self::infer_schema), also typing cells that hold text — every CSV field,
    /// or numbers stored as text: integers, decimals, `true`/`false` and ISO dates or date-times,
    /// when the text has exactly that shape. Leading-zero codes such as `00123` stay text.
    pub fn infer_schema_parse_text(
        &self,
        header_row: i32,
        sample_size: i32,
    ) -> Result<Vec<InferredColumn>, Error> {
        self.infer_schema_flags(header_row, sample_size, crate::XL_INFER_PARSE_TEXT)
    }

    fn infer_schema_flags(
        &self,
        header_row: i32,
        sample_size: i32,
        flags: i32,
    ) -> Result<Vec<InferredColumn>, Error> {
        let mut schema = XlInferredSchema {
            columns: std::ptr::null_mut(),
            column_count: 0,
        };
        check(unsafe {
            crate::xl_infer_schema(
                self.workbook.handle,
                self.index,
                header_row,
                sample_size,
                flags,
                &mut schema,
            )
        })?;

        let columns = unsafe { copy_inferred(&schema) };
        unsafe { crate::xl_free_schema(&mut schema) };
        Ok(columns)
    }

    pub(crate) fn handle(&self) -> *mut XlWorkbook {
        self.workbook.handle
    }
}

/// The sheet's position only - reading its name would be a native call inside `Debug`.
impl std::fmt::Debug for Sheet<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Sheet").field("index", &self.index).finish()
    }
}

/// Deep-copies a native-owned inferred schema into owned Rust values, so the caller can free the
/// native allocation immediately.
///
/// # Safety
/// `schema` must be one `xl_infer_schema` returned `XL_OK` for, not yet passed to `xl_free_schema`.
unsafe fn copy_inferred(schema: &XlInferredSchema) -> Vec<InferredColumn> {
    if schema.columns.is_null() || schema.column_count <= 0 {
        return Vec::new();
    }
    let specs = std::slice::from_raw_parts(schema.columns, schema.column_count as usize);
    specs
        .iter()
        .map(|spec| InferredColumn {
            name: if spec.name_count <= 0 || spec.names.is_null() || spec.name_lens.is_null() {
                None
            } else {
                let name_ptr = *spec.names;
                let name_len = *spec.name_lens;
                if name_ptr.is_null() || name_len <= 0 {
                    None
                } else {
                    let bytes = std::slice::from_raw_parts(name_ptr, name_len as usize);
                    Some(String::from_utf8_lossy(bytes).into_owned())
                }
            },
            index: spec.index,
            column_type: spec.r#type,
            nullable: spec.nullable != 0,
        })
        .collect()
}

/// One column guessed by [`Sheet::infer_schema`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InferredColumn {
    /// Header text, or `None` when the column must be resolved by [`index`](Self::index) instead.
    pub name: Option<String>,
    pub index: i32,
    /// One of the `XL_T_*` constants.
    pub column_type: i32,
    pub nullable: bool,
}

impl Drop for Workbook {
    fn drop(&mut self) {
        if !self.handle.is_null() {
            unsafe {
                crate::xl_close(self.handle);
            }
            self.handle = std::ptr::null_mut();
        }
    }
}

/// Deliberately opaque: the only state here is a handle whose value means nothing outside the
/// native library, and printing it would invite treating it as an identity it is not.
impl std::fmt::Debug for Workbook {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Workbook")
            .field("open", &!self.handle.is_null())
            .finish()
    }
}

/// One field <-> column binding for `T`. Construct via `ExcelMapper::bindings()`.
pub struct ColumnBinding<T> {
    /// Candidate header names, in priority order — the first one present in the header row wins.
    pub names: &'static [&'static str],
    pub xl_type: i32,
    pub assign: fn(&mut T, &XlColumn, i64),
}

// Hand-written: `#[derive(Clone)]` would add a `T: Clone` bound the user's row struct need not meet.
impl<T> Clone for ColumnBinding<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for ColumnBinding<T> {}

/// Implemented by any struct `parse_sheet` can populate from a `parse_typed` result. Implement
/// `bindings()` by hand (mirroring `xl::ExcelMapper<T>` on the C++ side), or derive it with
/// `#[derive(ExcelMapper)]` (see `excelreader_derive`).
pub trait ExcelMapper: Sized {
    fn bindings() -> Vec<ColumnBinding<Self>>;
}

pub use excelreader_derive::ExcelMapper;

fn is_valid(col: &XlColumn, row: i64) -> bool {
    if col.validity.is_null() {
        return true;
    }
    unsafe {
        let byte = *col.validity.offset((row / 8) as isize);
        (byte & (1 << (row % 8))) != 0
    }
}

/// Guards every `column_*` accessor below.
///
/// These are safe `pub` functions that index into raw native buffers, so this check is what makes
/// them sound: without it a `row` past the column returns whatever sits after the allocation. The
/// type half catches the other class of mistake - reading an `XL_T_F64` buffer as `i64` is an
/// `ExcelMapper::bindings()` bug, not recoverable input.
#[inline]
fn check_access(col: &XlColumn, row: i64, expected_type: i32, accessor: &str) {
    assert_eq!(
        col.r#type, expected_type,
        "{accessor} called on a column of type {}",
        col.r#type
    );
    assert!(
        row >= 0 && row < col.length,
        "{accessor}: row {row} is out of bounds for a column of length {}",
        col.length
    );
}

/// Reads column `col` at `row` as a `&str`.
///
/// The ABI documents every string it returns as UTF-8, but this validates rather than trusting it:
/// the bytes cross an FFI boundary from a binary resolved at build time, and `from_utf8_unchecked`
/// on a value that turns out not to be UTF-8 is undefined behavior, not merely a wrong answer.
/// Validation is a linear scan over bytes already in cache.
///
/// # Panics
/// If `col` is not an `XL_T_STRING` column, if `row` is out of bounds, or if the native library
/// returned bytes that are not valid UTF-8 (an ABI contract violation).
pub fn column_str(col: &XlColumn, row: i64) -> &str {
    check_access(col, row, XL_T_STRING, "column_str");
    unsafe {
        let offsets = col.values as *const i32;
        let start = *offsets.offset(row as isize);
        let end = *offsets.offset(row as isize + 1);
        let bytes =
            std::slice::from_raw_parts(col.data.offset(start as isize), (end - start) as usize);
        std::str::from_utf8(bytes)
            .expect("native library returned a non-UTF-8 string, violating the ABI contract")
    }
}

/// # Panics
/// If `col` is not an `XL_T_I64` column, or `row` is out of bounds.
pub fn column_i64(col: &XlColumn, row: i64) -> i64 {
    check_access(col, row, XL_T_I64, "column_i64");
    unsafe { *(col.values as *const i64).offset(row as isize) }
}

/// # Panics
/// If `col` is not an `XL_T_F64` column, or `row` is out of bounds.
pub fn column_f64(col: &XlColumn, row: i64) -> f64 {
    check_access(col, row, XL_T_F64, "column_f64");
    unsafe { *(col.values as *const f64).offset(row as isize) }
}

/// # Panics
/// If `col` is not an `XL_T_BOOL` column, or `row` is out of bounds.
pub fn column_bool(col: &XlColumn, row: i64) -> bool {
    check_access(col, row, XL_T_BOOL, "column_bool");
    unsafe { *(col.values as *const u8).offset(row as isize) != 0 }
}

/// # Panics
/// If `col` is not an `XL_T_DATE` column, or `row` is out of bounds.
pub fn column_date(col: &XlColumn, row: i64) -> Date {
    check_access(col, row, XL_T_DATE, "column_date");
    Date::new(unsafe { *(col.values as *const i32).offset(row as isize) })
}

/// # Panics
/// If `col` is not an `XL_T_TIME` column, or `row` is out of bounds.
pub fn column_time(col: &XlColumn, row: i64) -> Time {
    check_access(col, row, XL_T_TIME, "column_time");
    Time::new(unsafe { *(col.values as *const i64).offset(row as isize) })
}

/// # Panics
/// If `col` is not an `XL_T_TIMESTAMP` column, or `row` is out of bounds.
pub fn column_timestamp(col: &XlColumn, row: i64) -> Timestamp {
    check_access(col, row, XL_T_TIMESTAMP, "column_timestamp");
    Timestamp::new(unsafe { *(col.values as *const i64).offset(row as isize) })
}

/// Owns a `parse_typed` result. Frees the native table on `Drop`. `iter()` builds one `T` per call
/// to `next()` from the columnar buffers - no upfront `Vec<T>` allocation beyond what
/// `xl_parse_typed` itself already made.
pub struct TableView<T: ExcelMapper> {
    table: XlTable,
    bindings: Vec<ColumnBinding<T>>,
    _marker: PhantomData<T>,
}

impl<T: ExcelMapper> TableView<T> {
    pub fn len(&self) -> i64 {
        self.table.row_count
    }

    pub fn is_empty(&self) -> bool {
        self.table.row_count == 0
    }

    /// Builds `T` from row `row`, or `None` when `row` falls outside `0..len()`.
    ///
    /// Returning `Option` rather than `T` is what keeps this sound: the columnar buffers are raw
    /// native allocations, so an unchecked row would read past them from safe code.
    pub fn get(&self, row: i64) -> Option<T>
    where
        T: Default,
    {
        if row < 0 || row >= self.len() {
            return None;
        }
        let mut instance = T::default();
        let columns = unsafe {
            std::slice::from_raw_parts(self.table.columns, self.table.column_count as usize)
        };
        for (col, binding) in columns.iter().zip(self.bindings.iter()) {
            if is_valid(col, row) {
                (binding.assign)(&mut instance, col, row);
            }
        }
        Some(instance)
    }

    pub fn iter(&self) -> TableViewIter<'_, T>
    where
        T: Default,
    {
        TableViewIter { view: self, row: 0 }
    }
}

impl<T: ExcelMapper> Drop for TableView<T> {
    fn drop(&mut self) {
        unsafe {
            crate::xl_free_table(&mut self.table);
        }
    }
}

// SAFETY: plain native allocations, read only through &self, released by xl_free_table, which any
// thread may call. T appears only as fn pointers, never as a stored value.
unsafe impl<T: ExcelMapper> Send for TableView<T> {}
unsafe impl<T: ExcelMapper> Sync for TableView<T> {}

/// Shape only. Rendering the rows would mean materializing every `T`, which is the one thing this
/// type exists to avoid.
impl<T: ExcelMapper> std::fmt::Debug for TableView<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TableView")
            .field("rows", &self.table.row_count)
            .field("columns", &self.table.column_count)
            .finish_non_exhaustive()
    }
}

/// Iterator over the batches of one chunked typed read. Closes the native reader on `Drop`.
pub struct TypedChunks<'a, T: ExcelMapper> {
    reader: *mut crate::XlTypedReader,
    bindings: Vec<ColumnBinding<T>>,
    done: bool,
    _workbook: PhantomData<&'a Workbook>,
}

// SAFETY: a typed reader owns its native enumerator; ABI v6 lets it be used from any one thread
// at a time, which `&mut self` on `next` already guarantees.
unsafe impl<T: ExcelMapper> Send for TypedChunks<'_, T> {}

impl<T: ExcelMapper> Iterator for TypedChunks<'_, T> {
    type Item = Result<TableView<T>, Error>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }

        let mut table = XlTable {
            column_count: 0,
            row_count: 0,
            columns: std::ptr::null_mut(),
        };
        let status = unsafe { crate::xl_typed_reader_next(self.reader, &mut table) };
        if status == XL_EOF {
            self.done = true;
            return None;
        }
        if status != XL_OK {
            self.done = true;
            return Some(Err(last_error(status)));
        }

        if table.column_count as usize != self.bindings.len() {
            let column_count = table.column_count;
            unsafe { crate::xl_free_table(&mut table) };
            self.done = true;
            return Some(Err(Error::from_status(
                XL_ERROR,
                format!(
                    "xl_typed_reader_next returned {column_count} columns for {} specs",
                    self.bindings.len()
                ),
            )));
        }

        // ponytail: one small Vec of function pointers cloned per batch, not per row. Give
        Some(Ok(TableView {
            table,
            bindings: self.bindings.clone(),
            _marker: PhantomData,
        }))
    }
}

impl<T: ExcelMapper> Drop for TypedChunks<'_, T> {
    fn drop(&mut self) {
        unsafe { crate::xl_typed_reader_close(self.reader) };
    }
}

/// Progress only - the reader handle is opaque. Needed for `expect_err` on a `Result<Self, _>`.
impl<T: ExcelMapper> std::fmt::Debug for TypedChunks<'_, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TypedChunks")
            .field("columns", &self.bindings.len())
            .field("done", &self.done)
            .finish_non_exhaustive()
    }
}

pub struct TableViewIter<'a, T: ExcelMapper> {
    view: &'a TableView<T>,
    row: i64,
}

impl<T: ExcelMapper + Default> Iterator for TableViewIter<'_, T> {
    type Item = T;

    fn next(&mut self) -> Option<T> {
        let item = self.view.get(self.row)?;
        self.row += 1;
        Some(item)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = (self.view.len() - self.row).max(0) as usize;
        (remaining, Some(remaining))
    }
}

impl<T: ExcelMapper + Default> ExactSizeIterator for TableViewIter<'_, T> {}

/// Keeps the per-column name pointer/length vectors alive for as long as the `XlColumnSpec` array
/// that points into them. The two `_name_*` fields are never read - dropping them early would
/// leave `specs` holding dangling pointers, which is the whole reason they are stored here.
///
/// Also carries the `T::bindings()` this arena was built from, so callers that need both the flat
/// spec array (for the FFI call) and the typed bindings (for result-column lookups) can get both
/// from a single `T::bindings()` call instead of computing it twice.
pub(crate) struct SpecArena<T: ExcelMapper> {
    pub(crate) specs: Vec<XlColumnSpec>,
    pub(crate) bindings: Vec<ColumnBinding<T>>,
    _name_ptrs: Vec<Vec<*const u8>>,
    _name_lens: Vec<Vec<i32>>,
}

/// Lowers `T`'s ExcelMapper bindings into the flat `xl_column_spec` array both `xl_parse_typed` and
/// `xl_parse_arrow` take - their column-spec input is identical.
pub(crate) fn build_specs<T: ExcelMapper>() -> SpecArena<T> {
    let bindings = T::bindings();
    let name_ptrs: Vec<Vec<*const u8>> = bindings
        .iter()
        .map(|b| b.names.iter().map(|n| n.as_ptr()).collect())
        .collect();
    let name_lens: Vec<Vec<i32>> = bindings
        .iter()
        .map(|b| b.names.iter().map(|n| n.len() as i32).collect())
        .collect();
    let specs: Vec<XlColumnSpec> = bindings
        .iter()
        .enumerate()
        .map(|(i, b)| XlColumnSpec {
            names: name_ptrs[i].as_ptr(),
            name_lens: name_lens[i].as_ptr(),
            name_count: b.names.len() as i32,
            index: 0,
            r#type: b.xl_type,
            nullable: 1,
        })
        .collect();
    SpecArena {
        specs,
        bindings,
        _name_ptrs: name_ptrs,
        _name_lens: name_lens,
    }
}

/// Schema-driven columnar parse of one sheet, matching C++'s `xl::parse_sheet<T>`.
pub fn parse_sheet<T: ExcelMapper>(
    sheet: Sheet<'_>,
    header_row: i32,
) -> Result<TableView<T>, Error> {
    parse_sheet_parallel(sheet, header_row, 1)
}

/// [`parse_sheet`] with a degree of parallelism: `0` uses every processor, `1` is sequential, `n`
/// up to `n` threads, negative is an error. Only CSV is split; other formats read sequentially.
/// The table equals `parse_sheet`'s.
pub fn parse_sheet_parallel<T: ExcelMapper>(
    sheet: Sheet<'_>,
    header_row: i32,
    degree_of_parallelism: i32,
) -> Result<TableView<T>, Error> {
    let arena = build_specs::<T>();
    let bindings = arena.bindings;
    let mut table = XlTable {
        column_count: 0,
        row_count: 0,
        columns: std::ptr::null_mut(),
    };
    unsafe {
        let status = crate::xl_parse_typed(
            sheet.handle(),
            sheet.index(),
            arena.specs.as_ptr(),
            arena.specs.len() as i32,
            header_row,
            degree_of_parallelism,
            &mut table,
        );
        if status != XL_OK {
            return Err(last_error(status));
        }
    }

    if table.column_count as usize != bindings.len() {
        let column_count = table.column_count;
        unsafe { crate::xl_free_table(&mut table) };
        return Err(Error::from_status(
            XL_ERROR,
            format!(
                "xl_parse_typed returned {column_count} columns for {} specs",
                bindings.len()
            ),
        ));
    }

    Ok(TableView {
        table,
        bindings,
        _marker: PhantomData,
    })
}