Skip to main content

excel_api/
borrowed.rs

1//! Read-only views over values supplied by Excel for one callback invocation.
2//!
3//! The only entry point from the raw ABI is [`RawExcelValue::from_callback`].
4//! It is unsafe because Rust cannot prove the validity or lifetime of the
5//! pointer-bearing members of an `XLOPER12`. Once that boundary has been
6//! audited by the callback thunk, decoding and observation are safe.
7//!
8//! Callback views cannot be sent to another thread:
9//!
10//! ```compile_fail
11//! use excel_api::RawExcelValue;
12//!
13//! fn require_send<T: Send>() {}
14//! require_send::<RawExcelValue<'static>>();
15//! ```
16//!
17//! Nor can their callback lifetime be extended:
18//!
19//! ```compile_fail
20//! use excel_api::{ExcelValueRef, RawExcelValue};
21//!
22//! fn escape(raw: &RawExcelValue<'_>) -> ExcelValueRef<'static> {
23//!     raw.decode().unwrap()
24//! }
25//! ```
26
27use core::{
28    marker::PhantomData,
29    mem::size_of,
30    ptr::{self, NonNull},
31    slice,
32};
33
34use excel_api_sys::{
35    COL, EXCEL12_MAX_COLUMN, EXCEL12_MAX_COLUMNS, EXCEL12_MAX_ROW, EXCEL12_MAX_ROWS,
36    EXCEL12_MAX_STRING_CODE_UNITS, IDSHEET, RW, XCHAR, XLBIT_DLL_FREE, XLBIT_XL_FREE, XLOPER12,
37    XLREF12, XLTYPE_BIG_DATA, XLTYPE_BOOL, XLTYPE_ERR, XLTYPE_FLOW, XLTYPE_INT, XLTYPE_MISSING,
38    XLTYPE_MULTI, XLTYPE_NIL, XLTYPE_NUM, XLTYPE_REF, XLTYPE_SREF, XLTYPE_STR, XlError,
39};
40
41use crate::ExcelError;
42
43type CallbackMarker<'call> = PhantomData<(&'call XLOPER12, *mut ())>;
44
45/// Why a raw callback value could not be represented as a safe borrowed view.
46#[derive(Clone, Debug, Eq, PartialEq)]
47pub enum DecodeError {
48    /// The value tag contains unsupported or mutually inconsistent bits.
49    MalformedType(u32),
50    /// The value uses a valid Excel tag that this safe view does not represent.
51    UnsupportedType(u32),
52    /// The numeric Excel error code has no corresponding [`ExcelError`].
53    InvalidError(i32),
54    /// A string-tagged value has a null payload pointer.
55    NullStringPointer,
56    /// A string length exceeds Excel's documented UTF-16 limit.
57    StringTooLong(usize),
58    /// A direct string lacked a terminator within Excel's bounded limit.
59    UnterminatedString,
60    /// Array dimensions were invalid or overflowed.
61    MalformedArrayDimensions {
62        /// Raw Excel row count.
63        rows: RW,
64        /// Raw Excel column count.
65        columns: COL,
66    },
67    /// The validated array extent cannot be represented safely by Rust.
68    ArrayTooLarge,
69    /// An array-tagged value has a null element pointer.
70    NullArrayPointer,
71    /// An array element attempted to contain another array.
72    NestedArray,
73    /// An array element attempted to contain an Excel reference.
74    ReferenceInArray,
75    /// An `xltypeSRef` value did not contain exactly one area.
76    InvalidSingleReferenceCount(u16),
77    /// A reference-tagged value has a null reference table pointer.
78    NullReferencePointer,
79    /// An `xltypeRef` value declared no reference areas.
80    EmptyMultiReference,
81    /// A reference area has invalid or out-of-range row or column bounds.
82    MalformedReferenceArea,
83}
84
85/// An `XLOPER12` whose storage is owned by Excel for one callback invocation.
86///
87/// This wrapper is deliberately neither `Clone`, `Copy`, `Send`, nor `Sync`.
88///
89/// ```compile_fail
90/// use excel_api::RawExcelValue;
91/// fn require_sync<T: Sync>() {}
92/// require_sync::<RawExcelValue<'static>>();
93/// ```
94///
95/// ```compile_fail
96/// use excel_api::RawExcelValue;
97/// fn require_clone<T: Clone>() {}
98/// require_clone::<RawExcelValue<'static>>();
99/// ```
100#[derive(Debug)]
101pub struct RawExcelValue<'call> {
102    raw: NonNull<XLOPER12>,
103    _callback: CallbackMarker<'call>,
104}
105
106impl<'call> RawExcelValue<'call> {
107    /// Establishes the single unsafe boundary for a callback argument.
108    ///
109    /// # Safety
110    ///
111    /// `raw` and every pointer-bearing member reachable from it must describe
112    /// initialized, properly aligned SDK storage that remains readable and is
113    /// not mutated for all of `'call`. Counted strings must include their
114    /// prefix and payload, null-terminated direct strings have separate
115    /// constructors, multis must contain `rows * columns` initialized elements,
116    /// and multi-references must contain `count` initialized areas.
117    pub unsafe fn from_callback(raw: &'call XLOPER12) -> Self {
118        Self {
119            raw: NonNull::from(raw),
120            _callback: PhantomData,
121        }
122    }
123
124    /// Decodes the raw value after masking Excel's ownership bits.
125    pub fn decode(&self) -> Result<ExcelValueRef<'call>, DecodeError> {
126        // SAFETY: `from_callback` establishes readability and immutability for
127        // the complete callback lifetime.
128        unsafe { decode_xloper(self.raw, DecodeContext::TopLevel) }
129    }
130}
131
132/// A decoded, read-only Excel callback value.
133///
134/// ```compile_fail
135/// use excel_api::ExcelValueRef;
136/// fn require_send<T: Send>() {}
137/// require_send::<ExcelValueRef<'static>>();
138/// ```
139///
140/// ```compile_fail
141/// use excel_api::ExcelValueRef;
142/// fn require_sync<T: Sync>() {}
143/// require_sync::<ExcelValueRef<'static>>();
144/// ```
145///
146/// ```compile_fail
147/// use excel_api::ExcelValueRef;
148/// fn require_clone<T: Clone>() {}
149/// require_clone::<ExcelValueRef<'static>>();
150/// ```
151#[derive(Debug)]
152pub enum ExcelValueRef<'call> {
153    /// A binary floating-point scalar.
154    Number(f64),
155    /// A callback-borrowed UTF-16 string view.
156    Text(ExcelStr<'call>),
157    /// A Boolean scalar.
158    Boolean(bool),
159    /// A callback-borrowed worksheet reference.
160    Reference(ExcelReference<'call>),
161    /// A controlled Excel worksheet error.
162    Error(ExcelError),
163    /// A callback-borrowed two-dimensional array view.
164    Array(ExcelArrayView<'call>),
165    /// An omitted argument.
166    Missing(ExcelMissing),
167    /// Excel's distinct empty value.
168    Nil(ExcelNil),
169    /// Excel's 32-bit integer scalar.
170    Integer(i32),
171}
172
173impl ExcelValueRef<'_> {
174    /// Returns a stable, human-readable name for this variant's value kind.
175    pub const fn kind_name(&self) -> &'static str {
176        match self {
177            Self::Number(_) => "number",
178            Self::Text(_) => "text",
179            Self::Boolean(_) => "boolean",
180            Self::Reference(_) => "reference",
181            Self::Error(_) => "error",
182            Self::Array(_) => "array",
183            Self::Missing(_) => "missing",
184            Self::Nil(_) => "nil",
185            Self::Integer(_) => "integer",
186        }
187    }
188}
189
190/// Borrowed UTF-16 code units. No Unicode conversion is performed.
191///
192/// ```compile_fail
193/// use excel_api::ExcelStr;
194/// fn require_send<T: Send>() {}
195/// require_send::<ExcelStr<'static>>();
196/// ```
197///
198/// ```compile_fail
199/// use excel_api::ExcelStr;
200/// fn require_sync<T: Sync>() {}
201/// require_sync::<ExcelStr<'static>>();
202/// ```
203///
204/// ```compile_fail
205/// use excel_api::ExcelStr;
206/// fn require_clone<T: Clone>() {}
207/// require_clone::<ExcelStr<'static>>();
208/// ```
209#[derive(Debug)]
210pub struct ExcelStr<'call> {
211    payload: NonNull<XCHAR>,
212    len: usize,
213    _callback: CallbackMarker<'call>,
214}
215
216impl<'call> ExcelStr<'call> {
217    /// Parses a registered counted direct UTF-16 argument.
218    ///
219    /// # Safety
220    ///
221    /// `counted` must be aligned, readable, and immutable for `'call`. It must
222    /// contain a readable length prefix followed by that many code units.
223    pub unsafe fn from_counted_direct(counted: &'call XCHAR) -> Result<Self, DecodeError> {
224        // SAFETY: guaranteed by this function's caller.
225        unsafe { parse_direct_counted(NonNull::from(counted)) }
226    }
227
228    /// Parses a registered null-terminated direct UTF-16 argument.
229    ///
230    /// Scanning is bounded by Excel's 32,767-code-unit string limit.
231    ///
232    /// # Safety
233    ///
234    /// `terminated` must be aligned, readable, and immutable for `'call`
235    /// through the first NUL or through index 32,767 inclusive.
236    pub unsafe fn from_null_terminated_direct(
237        terminated: &'call XCHAR,
238    ) -> Result<Self, DecodeError> {
239        // SAFETY: guaranteed by this function's caller.
240        unsafe { parse_direct_null_terminated(NonNull::from(terminated)) }
241    }
242
243    /// Returns the number of UTF-16 code units, not Unicode scalar values.
244    pub const fn len(&self) -> usize {
245        self.len
246    }
247
248    /// Returns whether the borrowed payload contains no UTF-16 code units.
249    pub const fn is_empty(&self) -> bool {
250        self.len == 0
251    }
252
253    /// Returns the exact UTF-16 payload, excluding a prefix or terminator.
254    pub fn as_utf16(&self) -> &'call [u16] {
255        // SAFETY: every constructor validates the payload extent, and the
256        // callback contract keeps it readable and immutable for `'call`.
257        unsafe { slice::from_raw_parts(self.payload.as_ptr(), self.len) }
258    }
259}
260
261/// Marker for an omitted function argument (`xltypeMissing`).
262#[derive(Debug, Eq, PartialEq)]
263pub struct ExcelMissing {
264    _private: (),
265}
266
267/// Marker for an empty Excel value (`xltypeNil`).
268#[derive(Debug, Eq, PartialEq)]
269pub struct ExcelNil {
270    _private: (),
271}
272
273/// A flat row-major `xltypeMulti` view.
274///
275/// ```compile_fail
276/// use excel_api::ExcelArrayView;
277/// fn require_send<T: Send>() {}
278/// require_send::<ExcelArrayView<'static>>();
279/// ```
280///
281/// ```compile_fail
282/// use excel_api::ExcelArrayView;
283/// fn require_sync<T: Sync>() {}
284/// require_sync::<ExcelArrayView<'static>>();
285/// ```
286///
287/// ```compile_fail
288/// use excel_api::ExcelArrayView;
289/// fn require_clone<T: Clone>() {}
290/// require_clone::<ExcelArrayView<'static>>();
291/// ```
292#[derive(Debug)]
293pub struct ExcelArrayView<'call> {
294    elements: NonNull<XLOPER12>,
295    rows: usize,
296    columns: usize,
297    _callback: CallbackMarker<'call>,
298}
299
300impl<'call> ExcelArrayView<'call> {
301    /// Returns `(rows, columns)` for this rectangular callback array.
302    pub const fn dimensions(&self) -> (usize, usize) {
303        (self.rows, self.columns)
304    }
305
306    /// Returns the number of rows.
307    pub const fn row_count(&self) -> usize {
308        self.rows
309    }
310
311    /// Returns the number of columns.
312    pub const fn column_count(&self) -> usize {
313        self.columns
314    }
315
316    /// Decodes one element, or returns `Ok(None)` when the index is outside it.
317    ///
318    /// The returned view borrows the same Excel callback storage as this array.
319    pub fn get(
320        &self,
321        row: usize,
322        column: usize,
323    ) -> Result<Option<ExcelValueRef<'call>>, DecodeError> {
324        if row >= self.rows || column >= self.columns {
325            return Ok(None);
326        }
327        let index = row * self.columns + column;
328        self.decode_index(index).map(Some)
329    }
330
331    /// Iterates decoded elements in `row`, or returns `None` for an invalid row.
332    pub fn row(&self, row: usize) -> Option<ExcelArrayElements<'_, 'call>> {
333        (row < self.rows).then_some(ExcelArrayElements {
334            array: self,
335            next: row * self.columns,
336            remaining: self.columns,
337            stride: 1,
338        })
339    }
340
341    /// Iterates decoded elements in `column`, or returns `None` for an invalid column.
342    pub fn column(&self, column: usize) -> Option<ExcelArrayElements<'_, 'call>> {
343        (column < self.columns).then_some(ExcelArrayElements {
344            array: self,
345            next: column,
346            remaining: self.rows,
347            stride: self.columns,
348        })
349    }
350
351    /// Iterates the rows in row-major order.
352    pub fn rows(&self) -> ExcelArrayRows<'_, 'call> {
353        ExcelArrayRows {
354            array: self,
355            next: 0,
356        }
357    }
358
359    /// Iterates the columns in column-major order.
360    pub fn columns(&self) -> ExcelArrayColumns<'_, 'call> {
361        ExcelArrayColumns {
362            array: self,
363            next: 0,
364        }
365    }
366
367    fn decode_index(&self, index: usize) -> Result<ExcelValueRef<'call>, DecodeError> {
368        // SAFETY: array construction validates the allocation extent and this
369        // method only receives an in-bounds linear index.
370        let element = unsafe { NonNull::new_unchecked(self.elements.as_ptr().add(index)) };
371        // SAFETY: the array callback contract covers every initialized element.
372        unsafe { decode_xloper(element, DecodeContext::ArrayElement) }
373    }
374
375    fn validate_elements(&self) -> Result<(), DecodeError> {
376        let count = self.rows * self.columns;
377        for index in 0..count {
378            self.decode_index(index)?;
379        }
380        Ok(())
381    }
382}
383
384/// Elements in one row or column of an Excel array.
385#[derive(Debug)]
386pub struct ExcelArrayElements<'view, 'call> {
387    array: &'view ExcelArrayView<'call>,
388    next: usize,
389    remaining: usize,
390    stride: usize,
391}
392
393impl<'call> Iterator for ExcelArrayElements<'_, 'call> {
394    type Item = Result<ExcelValueRef<'call>, DecodeError>;
395
396    fn next(&mut self) -> Option<Self::Item> {
397        if self.remaining == 0 {
398            return None;
399        }
400        let index = self.next;
401        self.next += self.stride;
402        self.remaining -= 1;
403        Some(self.array.decode_index(index))
404    }
405
406    fn size_hint(&self) -> (usize, Option<usize>) {
407        (self.remaining, Some(self.remaining))
408    }
409}
410
411impl ExactSizeIterator for ExcelArrayElements<'_, '_> {}
412
413/// Iterator over an array's rows.
414#[derive(Debug)]
415pub struct ExcelArrayRows<'view, 'call> {
416    array: &'view ExcelArrayView<'call>,
417    next: usize,
418}
419
420impl<'view, 'call> Iterator for ExcelArrayRows<'view, 'call> {
421    type Item = ExcelArrayElements<'view, 'call>;
422
423    fn next(&mut self) -> Option<Self::Item> {
424        let row = self.next;
425        let result = self.array.row(row)?;
426        self.next += 1;
427        Some(result)
428    }
429
430    fn size_hint(&self) -> (usize, Option<usize>) {
431        let remaining = self.array.rows - self.next;
432        (remaining, Some(remaining))
433    }
434}
435
436impl ExactSizeIterator for ExcelArrayRows<'_, '_> {}
437
438/// Iterator over an array's columns.
439#[derive(Debug)]
440pub struct ExcelArrayColumns<'view, 'call> {
441    array: &'view ExcelArrayView<'call>,
442    next: usize,
443}
444
445impl<'view, 'call> Iterator for ExcelArrayColumns<'view, 'call> {
446    type Item = ExcelArrayElements<'view, 'call>;
447
448    fn next(&mut self) -> Option<Self::Item> {
449        let column = self.next;
450        let result = self.array.column(column)?;
451        self.next += 1;
452        Some(result)
453    }
454
455    fn size_hint(&self) -> (usize, Option<usize>) {
456        let remaining = self.array.columns - self.next;
457        (remaining, Some(remaining))
458    }
459}
460
461impl ExactSizeIterator for ExcelArrayColumns<'_, '_> {}
462
463/// A reference-preserving callback value.
464///
465/// ```compile_fail
466/// use excel_api::ExcelReference;
467/// fn require_send<T: Send>() {}
468/// require_send::<ExcelReference<'static>>();
469/// ```
470///
471/// ```compile_fail
472/// use excel_api::ExcelReference;
473/// fn require_sync<T: Sync>() {}
474/// require_sync::<ExcelReference<'static>>();
475/// ```
476///
477/// ```compile_fail
478/// use excel_api::ExcelReference;
479/// fn require_clone<T: Clone>() {}
480/// require_clone::<ExcelReference<'static>>();
481/// ```
482#[derive(Debug)]
483pub enum ExcelReference<'call> {
484    /// One inline current-sheet area.
485    Single(ExcelSingleReference<'call>),
486    /// One or more explicit-sheet areas.
487    Multiple(ExcelMultiReference<'call>),
488}
489
490/// An inline, current-sheet `xltypeSRef`.
491#[derive(Debug)]
492pub struct ExcelSingleReference<'call> {
493    area: ExcelReferenceArea<'call>,
494}
495
496impl<'call> ExcelSingleReference<'call> {
497    /// Returns the sole rectangular area without copying callback storage.
498    pub const fn area(&self) -> &ExcelReferenceArea<'call> {
499        &self.area
500    }
501}
502
503/// An explicit-sheet, one-or-more-area `xltypeRef`.
504#[derive(Debug)]
505pub struct ExcelMultiReference<'call> {
506    areas: NonNull<XLREF12>,
507    area_count: usize,
508    sheet_id: IDSHEET,
509    _callback: CallbackMarker<'call>,
510}
511
512impl<'call> ExcelMultiReference<'call> {
513    /// Returns Excel's identifier for the referenced worksheet.
514    pub const fn sheet_id(&self) -> IDSHEET {
515        self.sheet_id
516    }
517
518    /// Returns the number of rectangular areas in this reference.
519    pub const fn area_count(&self) -> usize {
520        self.area_count
521    }
522
523    /// Returns a copied view of the indexed area, if it exists.
524    pub fn area(&self, index: usize) -> Option<ExcelReferenceArea<'call>> {
525        if index >= self.area_count {
526            return None;
527        }
528        // SAFETY: the callback contract guarantees `area_count` initialized
529        // entries and the bounds check keeps this pointer within them.
530        let area = unsafe { NonNull::new_unchecked(self.areas.as_ptr().add(index)) };
531        Some(ExcelReferenceArea {
532            area,
533            _callback: PhantomData,
534        })
535    }
536
537    /// Iterates all referenced areas in Excel's table order.
538    pub fn areas(&self) -> ExcelReferenceAreas<'_, 'call> {
539        ExcelReferenceAreas {
540            reference: self,
541            next: 0,
542        }
543    }
544}
545
546/// One rectangular area within a reference.
547#[derive(Debug)]
548pub struct ExcelReferenceArea<'call> {
549    area: NonNull<XLREF12>,
550    _callback: CallbackMarker<'call>,
551}
552
553impl ExcelReferenceArea<'_> {
554    /// Returns the first included zero-based worksheet row.
555    pub fn first_row(&self) -> RW {
556        self.read().rwFirst
557    }
558
559    /// Returns the last included zero-based worksheet row.
560    pub fn last_row(&self) -> RW {
561        self.read().rwLast
562    }
563
564    /// Returns the first included zero-based worksheet column.
565    pub fn first_column(&self) -> COL {
566        self.read().colFirst
567    }
568
569    /// Returns the last included zero-based worksheet column.
570    pub fn last_column(&self) -> COL {
571        self.read().colLast
572    }
573
574    fn read(&self) -> XLREF12 {
575        // SAFETY: construction validates that this area is initialized and the
576        // callback contract prevents mutation for its lifetime.
577        unsafe { self.area.as_ptr().read() }
578    }
579}
580
581/// Iterator over the areas of an `xltypeRef`.
582#[derive(Debug)]
583pub struct ExcelReferenceAreas<'view, 'call> {
584    reference: &'view ExcelMultiReference<'call>,
585    next: usize,
586}
587
588impl<'call> Iterator for ExcelReferenceAreas<'_, 'call> {
589    type Item = ExcelReferenceArea<'call>;
590
591    fn next(&mut self) -> Option<Self::Item> {
592        let result = self.reference.area(self.next)?;
593        self.next += 1;
594        Some(result)
595    }
596
597    fn size_hint(&self) -> (usize, Option<usize>) {
598        let remaining = self.reference.area_count - self.next;
599        (remaining, Some(remaining))
600    }
601}
602
603impl ExactSizeIterator for ExcelReferenceAreas<'_, '_> {}
604
605#[derive(Clone, Copy)]
606enum DecodeContext {
607    TopLevel,
608    ArrayElement,
609}
610
611unsafe fn decode_xloper<'call>(
612    raw: NonNull<XLOPER12>,
613    context: DecodeContext,
614) -> Result<ExcelValueRef<'call>, DecodeError> {
615    // SAFETY: the caller carries the callback allocation invariant.
616    let xltype = unsafe { ptr::addr_of!((*raw.as_ptr()).xltype).read() };
617    let base_type = xltype & !(XLBIT_XL_FREE | XLBIT_DLL_FREE);
618
619    match base_type {
620        XLTYPE_NUM => {
621            // SAFETY: the validated tag selects the `num` union member.
622            let value = unsafe { ptr::addr_of!((*raw.as_ptr()).val.num).read() };
623            Ok(ExcelValueRef::Number(value))
624        }
625        XLTYPE_STR => {
626            // SAFETY: the validated tag selects the `str` union member.
627            let string = unsafe { ptr::addr_of!((*raw.as_ptr()).val.str).read() };
628            let string = NonNull::new(string).ok_or(DecodeError::NullStringPointer)?;
629            // SAFETY: the callback boundary guarantees the counted payload.
630            unsafe { parse_xloper_counted(string).map(ExcelValueRef::Text) }
631        }
632        XLTYPE_BOOL => {
633            // SAFETY: the validated tag selects the `xbool` union member.
634            let value = unsafe { ptr::addr_of!((*raw.as_ptr()).val.xbool).read() };
635            Ok(ExcelValueRef::Boolean(value != 0))
636        }
637        XLTYPE_REF => {
638            if matches!(context, DecodeContext::ArrayElement) {
639                return Err(DecodeError::ReferenceInArray);
640            }
641            // SAFETY: the validated tag selects the `mref` union member.
642            let value = unsafe { ptr::addr_of!((*raw.as_ptr()).val.mref).read() };
643            let reference = NonNull::new(value.lpmref).ok_or(DecodeError::NullReferencePointer)?;
644            // SAFETY: the callback boundary guarantees a readable XLMREF12.
645            let count = unsafe { ptr::addr_of!((*reference.as_ptr()).count).read() } as usize;
646            if count == 0 {
647                return Err(DecodeError::EmptyMultiReference);
648            }
649            // SAFETY: `reftbl` begins at this SDK-defined field address.
650            let areas = unsafe {
651                NonNull::new_unchecked(
652                    ptr::addr_of!((*reference.as_ptr()).reftbl)
653                        .cast::<XLREF12>()
654                        .cast_mut(),
655                )
656            };
657            validate_reference_areas(areas, count)?;
658            Ok(ExcelValueRef::Reference(ExcelReference::Multiple(
659                ExcelMultiReference {
660                    areas,
661                    area_count: count,
662                    sheet_id: value.idSheet,
663                    _callback: PhantomData,
664                },
665            )))
666        }
667        XLTYPE_ERR => {
668            // SAFETY: the validated tag selects the `err` union member.
669            let value = unsafe { ptr::addr_of!((*raw.as_ptr()).val.err).read() };
670            decode_error(value).map(ExcelValueRef::Error)
671        }
672        XLTYPE_FLOW => Err(DecodeError::UnsupportedType(base_type)),
673        XLTYPE_MULTI => {
674            if matches!(context, DecodeContext::ArrayElement) {
675                return Err(DecodeError::NestedArray);
676            }
677            // SAFETY: the validated tag selects the `array` union member.
678            let value = unsafe { ptr::addr_of!((*raw.as_ptr()).val.array).read() };
679            let (rows, columns) = validate_array_dimensions(value.rows, value.columns)?;
680            let elements = NonNull::new(value.lparray).ok_or(DecodeError::NullArrayPointer)?;
681            let array = ExcelArrayView {
682                elements,
683                rows,
684                columns,
685                _callback: PhantomData,
686            };
687            array.validate_elements()?;
688            Ok(ExcelValueRef::Array(array))
689        }
690        XLTYPE_MISSING => Ok(ExcelValueRef::Missing(ExcelMissing { _private: () })),
691        XLTYPE_NIL => Ok(ExcelValueRef::Nil(ExcelNil { _private: () })),
692        XLTYPE_SREF => {
693            if matches!(context, DecodeContext::ArrayElement) {
694                return Err(DecodeError::ReferenceInArray);
695            }
696            // SAFETY: the validated tag selects the `sref` union member.
697            let value = unsafe { ptr::addr_of!((*raw.as_ptr()).val.sref).read() };
698            if value.count != 1 {
699                return Err(DecodeError::InvalidSingleReferenceCount(value.count));
700            }
701            validate_reference_area(value.reference)?;
702            // SAFETY: this is the address of the inline `reference` field and
703            // the parent XLOPER12 remains fixed for the callback lifetime.
704            let area = unsafe {
705                NonNull::new_unchecked(ptr::addr_of!((*raw.as_ptr()).val.sref.reference).cast_mut())
706            };
707            Ok(ExcelValueRef::Reference(ExcelReference::Single(
708                ExcelSingleReference {
709                    area: ExcelReferenceArea {
710                        area,
711                        _callback: PhantomData,
712                    },
713                },
714            )))
715        }
716        XLTYPE_INT => {
717            // SAFETY: the validated tag selects the `w` union member.
718            let value = unsafe { ptr::addr_of!((*raw.as_ptr()).val.w).read() };
719            Ok(ExcelValueRef::Integer(value))
720        }
721        XLTYPE_BIG_DATA => Err(DecodeError::UnsupportedType(base_type)),
722        _ => Err(DecodeError::MalformedType(base_type)),
723    }
724}
725
726unsafe fn parse_xloper_counted<'call>(
727    counted: NonNull<XCHAR>,
728) -> Result<ExcelStr<'call>, DecodeError> {
729    // SAFETY: this parser's caller guarantees a readable counted XLOPER string.
730    unsafe { parse_counted_payload(counted) }
731}
732
733unsafe fn parse_direct_counted<'call>(
734    counted: NonNull<XCHAR>,
735) -> Result<ExcelStr<'call>, DecodeError> {
736    // SAFETY: this parser's caller guarantees a readable direct counted string.
737    unsafe { parse_counted_payload(counted) }
738}
739
740unsafe fn parse_counted_payload<'call>(
741    counted: NonNull<XCHAR>,
742) -> Result<ExcelStr<'call>, DecodeError> {
743    // SAFETY: the prefix is initialized and readable by the parser contract.
744    let len = unsafe { counted.as_ptr().read() } as usize;
745    if len > EXCEL12_MAX_STRING_CODE_UNITS {
746        return Err(DecodeError::StringTooLong(len));
747    }
748    // SAFETY: a counted string always has a prefix, so adding one stays at the
749    // payload start even when the logical payload is empty.
750    let payload = unsafe { NonNull::new_unchecked(counted.as_ptr().add(1)) };
751    Ok(ExcelStr {
752        payload,
753        len,
754        _callback: PhantomData,
755    })
756}
757
758unsafe fn parse_direct_null_terminated<'call>(
759    terminated: NonNull<XCHAR>,
760) -> Result<ExcelStr<'call>, DecodeError> {
761    for len in 0..=EXCEL12_MAX_STRING_CODE_UNITS {
762        // SAFETY: the parser contract guarantees readability through this
763        // bounded scan range or the first terminator.
764        if unsafe { terminated.as_ptr().add(len).read() } == 0 {
765            return Ok(ExcelStr {
766                payload: terminated,
767                len,
768                _callback: PhantomData,
769            });
770        }
771    }
772    Err(DecodeError::UnterminatedString)
773}
774
775fn validate_array_dimensions(rows: RW, columns: COL) -> Result<(usize, usize), DecodeError> {
776    if !(1..=EXCEL12_MAX_ROWS).contains(&rows) || !(1..=EXCEL12_MAX_COLUMNS).contains(&columns) {
777        return Err(DecodeError::MalformedArrayDimensions { rows, columns });
778    }
779    let rows = usize::try_from(rows).map_err(|_| DecodeError::ArrayTooLarge)?;
780    let columns = usize::try_from(columns).map_err(|_| DecodeError::ArrayTooLarge)?;
781    let count = rows
782        .checked_mul(columns)
783        .ok_or(DecodeError::ArrayTooLarge)?;
784    if count > isize::MAX as usize / size_of::<XLOPER12>() {
785        return Err(DecodeError::ArrayTooLarge);
786    }
787    Ok((rows, columns))
788}
789
790fn validate_reference_areas(areas: NonNull<XLREF12>, count: usize) -> Result<(), DecodeError> {
791    for index in 0..count {
792        // SAFETY: the multi-reference callback contract guarantees `count`
793        // initialized entries.
794        let area = unsafe { areas.as_ptr().add(index).read() };
795        validate_reference_area(area)?;
796    }
797    Ok(())
798}
799
800fn validate_reference_area(area: XLREF12) -> Result<(), DecodeError> {
801    let rows_valid = (0..=EXCEL12_MAX_ROW).contains(&area.rwFirst)
802        && (area.rwFirst..=EXCEL12_MAX_ROW).contains(&area.rwLast);
803    let columns_valid = (0..=EXCEL12_MAX_COLUMN).contains(&area.colFirst)
804        && (area.colFirst..=EXCEL12_MAX_COLUMN).contains(&area.colLast);
805    if rows_valid && columns_valid {
806        Ok(())
807    } else {
808        Err(DecodeError::MalformedReferenceArea)
809    }
810}
811
812fn decode_error(value: i32) -> Result<ExcelError, DecodeError> {
813    let value = match value {
814        excel_api_sys::xlerrNull => XlError::Null,
815        excel_api_sys::xlerrDiv0 => XlError::Div0,
816        excel_api_sys::xlerrValue => XlError::Value,
817        excel_api_sys::xlerrRef => XlError::Ref,
818        excel_api_sys::xlerrName => XlError::Name,
819        excel_api_sys::xlerrNum => XlError::Num,
820        excel_api_sys::xlerrNA => XlError::Na,
821        excel_api_sys::xlerrGettingData => XlError::GettingData,
822        _ => return Err(DecodeError::InvalidError(value)),
823    };
824    Ok(value.into())
825}
826
827#[cfg(test)]
828mod tests {
829    use core::ffi::c_void;
830
831    use excel_api_sys::{
832        XLMREF12, XLOPER12Array, XLOPER12BigData, XLOPER12BigDataHandle, XLOPER12MRef,
833        XLOPER12SRef, XLOPER12Value, xlbitDLLFree, xlbitXLFree, xltypeBigData, xltypeBool,
834        xltypeErr, xltypeFlow, xltypeInt, xltypeMissing, xltypeMulti, xltypeNil, xltypeNum,
835        xltypeRef, xltypeSRef, xltypeStr,
836    };
837
838    use super::*;
839
840    fn raw(value: XLOPER12Value, xltype: u32) -> XLOPER12 {
841        XLOPER12 { val: value, xltype }
842    }
843
844    fn decode(value: &XLOPER12) -> Result<ExcelValueRef<'_>, DecodeError> {
845        // SAFETY: each test keeps all referenced fixtures alive and immutable
846        // for the returned view's lifetime.
847        unsafe { RawExcelValue::from_callback(value) }.decode()
848    }
849
850    fn zeroed_value() -> XLOPER12Value {
851        // SAFETY: every union member consists only of integer or raw-pointer
852        // fields, for which the all-zero bit pattern is valid.
853        unsafe { core::mem::zeroed() }
854    }
855
856    #[test]
857    fn decodes_scalar_tags_and_masks_ownership_bits() {
858        let number = raw(
859            XLOPER12Value { num: 2.5 },
860            xltypeNum | xlbitXLFree | xlbitDLLFree,
861        );
862        assert!(matches!(decode(&number), Ok(ExcelValueRef::Number(2.5))));
863
864        let boolean = raw(XLOPER12Value { xbool: -1 }, xltypeBool);
865        assert!(matches!(decode(&boolean), Ok(ExcelValueRef::Boolean(true))));
866
867        let integer = raw(XLOPER12Value { w: -42 }, xltypeInt);
868        assert!(matches!(decode(&integer), Ok(ExcelValueRef::Integer(-42))));
869
870        for (raw_error, expected) in [
871            (excel_api_sys::xlerrNull, ExcelError::Null),
872            (excel_api_sys::xlerrDiv0, ExcelError::Div0),
873            (excel_api_sys::xlerrValue, ExcelError::Value),
874            (excel_api_sys::xlerrRef, ExcelError::Ref),
875            (excel_api_sys::xlerrName, ExcelError::Name),
876            (excel_api_sys::xlerrNum, ExcelError::Num),
877            (excel_api_sys::xlerrNA, ExcelError::Na),
878            (excel_api_sys::xlerrGettingData, ExcelError::GettingData),
879        ] {
880            let error = raw(XLOPER12Value { err: raw_error }, xltypeErr);
881            let Ok(ExcelValueRef::Error(actual)) = decode(&error) else {
882                panic!("expected error value");
883            };
884            assert_eq!(actual, expected);
885        }
886    }
887
888    #[test]
889    fn missing_and_nil_are_independent() {
890        let missing = raw(XLOPER12Value { w: 0 }, xltypeMissing);
891        let nil = raw(XLOPER12Value { w: 0 }, xltypeNil);
892        assert!(matches!(decode(&missing), Ok(ExcelValueRef::Missing(_))));
893        assert!(matches!(decode(&nil), Ok(ExcelValueRef::Nil(_))));
894    }
895
896    #[test]
897    fn parses_all_three_string_abis_without_conversion() {
898        let mut xloper_text = [3, b'A' as u16, 0, 0xD800];
899        let value = raw(
900            XLOPER12Value {
901                str: xloper_text.as_mut_ptr(),
902            },
903            xltypeStr,
904        );
905        let Ok(ExcelValueRef::Text(text)) = decode(&value) else {
906            panic!("expected text");
907        };
908        assert_eq!(text.as_utf16(), &[b'A' as u16, 0, 0xD800]);
909
910        let counted = [2, 0xD800, b'Z' as u16];
911        // SAFETY: `counted` contains its prefix and complete payload.
912        let direct = unsafe { ExcelStr::from_counted_direct(&counted[0]) }.unwrap();
913        assert_eq!(direct.as_utf16(), &[0xD800, b'Z' as u16]);
914
915        let terminated = [b'X' as u16, b'Y' as u16, 0, b'Z' as u16];
916        // SAFETY: the fixture contains a terminator within the bounded scan.
917        let direct = unsafe { ExcelStr::from_null_terminated_direct(&terminated[0]) }.unwrap();
918        assert_eq!(direct.as_utf16(), &[b'X' as u16, b'Y' as u16]);
919
920        let mut empty = [0_u16];
921        let value = raw(
922            XLOPER12Value {
923                str: empty.as_mut_ptr(),
924            },
925            xltypeStr,
926        );
927        let Ok(ExcelValueRef::Text(empty)) = decode(&value) else {
928            panic!("expected empty text");
929        };
930        assert!(empty.is_empty());
931        assert_eq!(empty.as_utf16(), &[]);
932    }
933
934    #[test]
935    fn rejects_malformed_strings() {
936        let mut too_long = [u16::MAX, 0];
937        let value = raw(
938            XLOPER12Value {
939                str: too_long.as_mut_ptr(),
940            },
941            xltypeStr,
942        );
943        assert!(matches!(
944            decode(&value),
945            Err(DecodeError::StringTooLong(65_535))
946        ));
947
948        let null = raw(
949            XLOPER12Value {
950                str: ptr::null_mut(),
951            },
952            xltypeStr,
953        );
954        assert!(matches!(decode(&null), Err(DecodeError::NullStringPointer)));
955
956        let unterminated = [1_u16; EXCEL12_MAX_STRING_CODE_UNITS + 1];
957        // SAFETY: the entire bounded scan range is initialized.
958        let result = unsafe { ExcelStr::from_null_terminated_direct(&unterminated[0]) };
959        assert!(matches!(result, Err(DecodeError::UnterminatedString)));
960    }
961
962    #[test]
963    fn array_supports_indexing_rows_and_columns() {
964        let mut elements = [
965            raw(XLOPER12Value { num: 1.0 }, xltypeNum),
966            raw(XLOPER12Value { num: 2.0 }, xltypeNum),
967            raw(XLOPER12Value { num: 3.0 }, xltypeNum),
968            raw(XLOPER12Value { num: 4.0 }, xltypeNum),
969        ];
970        let value = raw(
971            XLOPER12Value {
972                array: XLOPER12Array {
973                    lparray: elements.as_mut_ptr(),
974                    rows: 2,
975                    columns: 2,
976                },
977            },
978            xltypeMulti,
979        );
980        let Ok(ExcelValueRef::Array(array)) = decode(&value) else {
981            panic!("expected array");
982        };
983        assert_eq!(array.dimensions(), (2, 2));
984        assert!(matches!(
985            array.get(1, 0),
986            Ok(Some(ExcelValueRef::Number(3.0)))
987        ));
988        assert!(matches!(array.get(2, 0), Ok(None)));
989
990        let second_row: Vec<_> = array.row(1).unwrap().collect();
991        assert!(matches!(second_row[0], Ok(ExcelValueRef::Number(3.0))));
992        assert!(matches!(second_row[1], Ok(ExcelValueRef::Number(4.0))));
993
994        let second_column: Vec<_> = array.column(1).unwrap().collect();
995        assert!(matches!(second_column[0], Ok(ExcelValueRef::Number(2.0))));
996        assert!(matches!(second_column[1], Ok(ExcelValueRef::Number(4.0))));
997        assert_eq!(array.rows().len(), 2);
998        assert_eq!(array.columns().len(), 2);
999    }
1000
1001    #[test]
1002    fn rejects_malformed_array_dimensions_and_pointer() {
1003        for (rows, columns) in [(0, 1), (1, 0), (-1, 1), (1, -1), (EXCEL12_MAX_ROWS + 1, 1)] {
1004            let value = raw(
1005                XLOPER12Value {
1006                    array: XLOPER12Array {
1007                        lparray: ptr::null_mut(),
1008                        rows,
1009                        columns,
1010                    },
1011                },
1012                xltypeMulti,
1013            );
1014            assert!(matches!(
1015                decode(&value),
1016                Err(DecodeError::MalformedArrayDimensions {
1017                    rows: actual_rows,
1018                    columns: actual_columns,
1019                }) if actual_rows == rows && actual_columns == columns
1020            ));
1021        }
1022
1023        let value = raw(
1024            XLOPER12Value {
1025                array: XLOPER12Array {
1026                    lparray: ptr::null_mut(),
1027                    rows: 1,
1028                    columns: 1,
1029                },
1030            },
1031            xltypeMulti,
1032        );
1033        assert!(matches!(decode(&value), Err(DecodeError::NullArrayPointer)));
1034    }
1035
1036    #[test]
1037    fn rejects_nested_arrays_and_references_in_arrays() {
1038        let mut nested = raw(
1039            XLOPER12Value {
1040                array: XLOPER12Array {
1041                    lparray: ptr::null_mut(),
1042                    rows: 1,
1043                    columns: 1,
1044                },
1045            },
1046            xltypeMulti,
1047        );
1048        let outer = raw(
1049            XLOPER12Value {
1050                array: XLOPER12Array {
1051                    lparray: &mut nested,
1052                    rows: 1,
1053                    columns: 1,
1054                },
1055            },
1056            xltypeMulti,
1057        );
1058        assert!(matches!(decode(&outer), Err(DecodeError::NestedArray)));
1059
1060        let mut reference = raw(
1061            XLOPER12Value {
1062                sref: XLOPER12SRef {
1063                    count: 1,
1064                    reference: XLREF12::default(),
1065                },
1066            },
1067            xltypeSRef,
1068        );
1069        let outer = raw(
1070            XLOPER12Value {
1071                array: XLOPER12Array {
1072                    lparray: &mut reference,
1073                    rows: 1,
1074                    columns: 1,
1075                },
1076            },
1077            xltypeMulti,
1078        );
1079        assert!(matches!(decode(&outer), Err(DecodeError::ReferenceInArray)));
1080    }
1081
1082    #[test]
1083    fn represents_single_and_multi_references_distinctly() {
1084        let single = raw(
1085            XLOPER12Value {
1086                sref: XLOPER12SRef {
1087                    count: 1,
1088                    reference: XLREF12 {
1089                        rwFirst: 1,
1090                        rwLast: 2,
1091                        colFirst: 3,
1092                        colLast: 4,
1093                    },
1094                },
1095            },
1096            xltypeSRef,
1097        );
1098        let Ok(ExcelValueRef::Reference(ExcelReference::Single(single))) = decode(&single) else {
1099            panic!("expected single reference");
1100        };
1101        assert_eq!(single.area().first_row(), 1);
1102        assert_eq!(single.area().last_column(), 4);
1103
1104        let mut mref = XLMREF12 {
1105            count: 1,
1106            reftbl: [XLREF12 {
1107                rwFirst: 5,
1108                rwLast: 6,
1109                colFirst: 7,
1110                colLast: 8,
1111            }],
1112        };
1113        let multiple = raw(
1114            XLOPER12Value {
1115                mref: XLOPER12MRef {
1116                    lpmref: &mut mref,
1117                    idSheet: 99,
1118                },
1119            },
1120            xltypeRef,
1121        );
1122        let Ok(ExcelValueRef::Reference(ExcelReference::Multiple(multiple))) = decode(&multiple)
1123        else {
1124            panic!("expected multi reference");
1125        };
1126        assert_eq!(multiple.sheet_id(), 99);
1127        assert_eq!(multiple.area_count(), 1);
1128        assert_eq!(multiple.areas().next().unwrap().first_column(), 7);
1129    }
1130
1131    #[test]
1132    fn multi_reference_exposes_every_sdk_tail_area() {
1133        #[repr(C)]
1134        struct TwoAreaReference {
1135            count: u16,
1136            padding: u16,
1137            areas: [XLREF12; 2],
1138        }
1139
1140        let mut storage = TwoAreaReference {
1141            count: 2,
1142            padding: 0,
1143            areas: [
1144                XLREF12 {
1145                    rwFirst: 1,
1146                    rwLast: 1,
1147                    colFirst: 2,
1148                    colLast: 2,
1149                },
1150                XLREF12 {
1151                    rwFirst: 3,
1152                    rwLast: 4,
1153                    colFirst: 5,
1154                    colLast: 6,
1155                },
1156            ],
1157        };
1158        let value = raw(
1159            XLOPER12Value {
1160                mref: XLOPER12MRef {
1161                    lpmref: (&mut storage as *mut TwoAreaReference).cast::<XLMREF12>(),
1162                    idSheet: 7,
1163                },
1164            },
1165            xltypeRef,
1166        );
1167        let Ok(ExcelValueRef::Reference(ExcelReference::Multiple(reference))) = decode(&value)
1168        else {
1169            panic!("expected multi reference");
1170        };
1171        assert_eq!(reference.area_count(), 2);
1172        assert_eq!(reference.area(0).unwrap().first_row(), 1);
1173        assert_eq!(reference.area(1).unwrap().last_column(), 6);
1174        assert!(reference.area(2).is_none());
1175    }
1176
1177    #[test]
1178    fn validates_reference_shapes() {
1179        let invalid_count = raw(
1180            XLOPER12Value {
1181                sref: XLOPER12SRef {
1182                    count: 2,
1183                    reference: XLREF12::default(),
1184                },
1185            },
1186            xltypeSRef,
1187        );
1188        assert!(matches!(
1189            decode(&invalid_count),
1190            Err(DecodeError::InvalidSingleReferenceCount(2))
1191        ));
1192
1193        let invalid_area = raw(
1194            XLOPER12Value {
1195                sref: XLOPER12SRef {
1196                    count: 1,
1197                    reference: XLREF12 {
1198                        rwFirst: 2,
1199                        rwLast: 1,
1200                        colFirst: 0,
1201                        colLast: 0,
1202                    },
1203                },
1204            },
1205            xltypeSRef,
1206        );
1207        assert!(matches!(
1208            decode(&invalid_area),
1209            Err(DecodeError::MalformedReferenceArea)
1210        ));
1211    }
1212
1213    #[test]
1214    fn every_sdk_type_is_decoded_or_explicitly_rejected() {
1215        let flow = raw(XLOPER12Value { w: 0 }, xltypeFlow);
1216        assert!(matches!(
1217            decode(&flow),
1218            Err(DecodeError::UnsupportedType(value)) if value == xltypeFlow
1219        ));
1220
1221        let big_data = raw(
1222            XLOPER12Value {
1223                bigdata: XLOPER12BigData {
1224                    h: XLOPER12BigDataHandle {
1225                        hdata: ptr::null_mut::<c_void>(),
1226                    },
1227                    cbData: 0,
1228                },
1229            },
1230            xltypeBigData,
1231        );
1232        assert!(matches!(
1233            decode(&big_data),
1234            Err(DecodeError::UnsupportedType(value)) if value == xltypeBigData
1235        ));
1236
1237        let invalid_error = raw(XLOPER12Value { err: -1 }, xltypeErr);
1238        assert!(matches!(
1239            decode(&invalid_error),
1240            Err(DecodeError::InvalidError(-1))
1241        ));
1242    }
1243
1244    #[test]
1245    fn malformed_tags_are_not_interpreted_as_union_members() {
1246        for xltype in [
1247            0,
1248            xltypeNum | xltypeBool,
1249            xlbitXLFree,
1250            xlbitDLLFree,
1251            0x2000,
1252            0x8000_0000 | xltypeNum,
1253        ] {
1254            let value = raw(zeroed_value(), xltype);
1255            assert!(matches!(decode(&value), Err(DecodeError::MalformedType(_))));
1256        }
1257    }
1258
1259    #[test]
1260    fn malformed_type_fuzz_never_panics() {
1261        for xltype in 0_u32..=u16::MAX as u32 {
1262            // A zeroed union is a valid raw-pointer/integer bit pattern. Any
1263            // pointer-bearing recognized tag is rejected before dereference.
1264            let value = raw(zeroed_value(), xltype);
1265            let _ = decode(&value);
1266        }
1267        for xltype in [u32::MAX, 0x8000_0001, 0x0002_0000, 0xDEAD_BEEF] {
1268            let value = raw(zeroed_value(), xltype);
1269            let _ = decode(&value);
1270        }
1271    }
1272}