Skip to main content

excel_api/
return_plan.rs

1//! Pure, deterministic planning for future Excel ABI return storage.
2//!
3//! This module deliberately creates no raw pointers, backing buffers,
4//! ownership bits, or FFI values. A successful [`ReturnPlan`] owns the exact
5//! logical payload and enough validated metadata for Prompt 05 to materialize
6//! it without revisiting return policy.
7
8use core::mem::size_of;
9
10use crate::{ExcelArray, ExcelError, ExcelString, ExcelValue, ReturnError};
11
12const XLOPER12_BYTES: usize = size_of::<excel_api_sys::XLOPER12>();
13const XCHAR_BYTES: usize = size_of::<excel_api_sys::XCHAR>();
14
15/// Owned text source whose representation choice is retained by the plan.
16#[derive(Clone, Debug, Eq, PartialEq)]
17pub enum ReturnText {
18    /// UTF-8 text to encode as a counted UTF-16 Excel string during materialization.
19    Utf8(String),
20    /// Exact owned UTF-16 code units to preserve during materialization.
21    Utf16(ExcelString),
22}
23
24impl From<String> for ReturnText {
25    fn from(value: String) -> Self {
26        Self::Utf8(value)
27    }
28}
29
30impl From<&str> for ReturnText {
31    fn from(value: &str) -> Self {
32        Self::Utf8(value.to_owned())
33    }
34}
35
36impl From<ExcelString> for ReturnText {
37    fn from(value: ExcelString) -> Self {
38        Self::Utf16(value)
39    }
40}
41
42/// Fully owned logical value offered to the return planner.
43#[derive(Clone, Debug, PartialEq)]
44pub enum ExcelReturnValue {
45    /// A floating-point scalar return.
46    Number(f64),
47    /// A 32-bit integer scalar return.
48    Integer(i32),
49    /// A Boolean scalar return.
50    Boolean(bool),
51    /// A controlled worksheet error return.
52    Error(ExcelError),
53    /// Excel's omitted/missing return value.
54    Missing,
55    /// Excel's distinct empty (`xltypeNil`) return value.
56    Empty,
57    /// Owned text returned as a counted Excel string.
58    Text(ReturnText),
59    /// Owned rectangular dynamic-array return data.
60    Array(ExcelReturnArray),
61}
62
63impl ExcelReturnValue {
64    /// Validates this value using the default bounded return limits.
65    pub fn plan(self) -> Result<ReturnPlan, ReturnError> {
66        self.plan_with_limits(&ReturnLimits::default())
67    }
68
69    /// Validates this value into pointer-free planning data using `limits`.
70    pub fn plan_with_limits(self, limits: &ReturnLimits) -> Result<ReturnPlan, ReturnError> {
71        Planner::new(limits).plan(self)
72    }
73}
74
75impl From<ExcelValue> for ExcelReturnValue {
76    fn from(value: ExcelValue) -> Self {
77        match value {
78            ExcelValue::Number(value) => Self::Number(value),
79            ExcelValue::Integer(value) => Self::Integer(value),
80            ExcelValue::Boolean(value) => Self::Boolean(value),
81            ExcelValue::Error(value) => Self::Error(value),
82            ExcelValue::Missing => Self::Missing,
83            ExcelValue::Empty => Self::Empty,
84            ExcelValue::Text(value) => Self::Text(ReturnText::Utf16(value)),
85            ExcelValue::Array(value) => Self::Array(value.into()),
86        }
87    }
88}
89
90impl From<ExcelArray> for ExcelReturnValue {
91    fn from(value: ExcelArray) -> Self {
92        Self::Array(value.into())
93    }
94}
95
96impl From<ExcelString> for ExcelReturnValue {
97    fn from(value: ExcelString) -> Self {
98        Self::Text(value.into())
99    }
100}
101
102impl From<ReturnText> for ExcelReturnValue {
103    fn from(value: ReturnText) -> Self {
104        Self::Text(value)
105    }
106}
107
108impl From<String> for ExcelReturnValue {
109    fn from(value: String) -> Self {
110        Self::Text(value.into())
111    }
112}
113
114impl From<&str> for ExcelReturnValue {
115    fn from(value: &str) -> Self {
116        Self::Text(value.into())
117    }
118}
119
120impl From<ExcelArray> for ExcelReturnArray {
121    fn from(value: ExcelArray) -> Self {
122        let (rows, columns, values) = value.into_parts();
123        Self {
124            rows,
125            columns,
126            values: values
127                .into_vec()
128                .into_iter()
129                .map(ExcelReturnValue::from)
130                .collect(),
131        }
132    }
133}
134
135/// Owned flat rectangular logical return array.
136///
137/// Construction validates shape but deliberately leaves return-specific ABI,
138/// nesting, and resource checks to [`ExcelReturnValue::plan_with_limits`].
139#[derive(Clone, Debug, PartialEq)]
140pub struct ExcelReturnArray {
141    rows: usize,
142    columns: usize,
143    values: Box<[ExcelReturnValue]>,
144}
145
146impl ExcelReturnArray {
147    /// Creates a flat row-major array after validating `rows * columns`.
148    pub fn new(
149        rows: usize,
150        columns: usize,
151        values: impl Into<Box<[ExcelReturnValue]>>,
152    ) -> Result<Self, ReturnError> {
153        let values = values.into();
154        let expected = rows
155            .checked_mul(columns)
156            .ok_or(ReturnError::ArrayElementCountOverflow { rows, columns })?;
157        if expected != values.len() {
158            return Err(ReturnError::InvalidArrayShape {
159                rows,
160                columns,
161                elements: values.len(),
162            });
163        }
164        Ok(Self {
165            rows,
166            columns,
167            values,
168        })
169    }
170
171    /// Returns the row count.
172    pub const fn rows(&self) -> usize {
173        self.rows
174    }
175
176    /// Returns the column count.
177    pub const fn columns(&self) -> usize {
178        self.columns
179    }
180
181    /// Returns the flat row-major element count.
182    pub const fn len(&self) -> usize {
183        self.values.len()
184    }
185
186    /// Returns whether this array contains no elements.
187    pub const fn is_empty(&self) -> bool {
188        self.values.is_empty()
189    }
190
191    /// Returns the owned values in flat row-major order.
192    pub fn values(&self) -> &[ExcelReturnValue] {
193        &self.values
194    }
195}
196
197/// Independent project limits for constructing ordinary Rust-created returns.
198#[derive(Clone, Copy, Debug, Eq, PartialEq)]
199pub struct ReturnLimits {
200    /// Maximum UTF-16 code units in one returned string.
201    pub max_string_code_units: usize,
202    /// Maximum elements in one returned array.
203    pub max_array_elements: usize,
204    /// Maximum ABI storage bytes described by one plan.
205    pub max_total_bytes: usize,
206    /// Maximum separate backing allocations described by one plan.
207    pub max_allocations: usize,
208    /// Maximum recursive planning depth.
209    pub max_depth: usize,
210}
211
212impl ReturnLimits {
213    /// Conservative limits used by [`Default`].
214    pub const DEFAULT: Self = Self {
215        max_string_code_units: excel_api_sys::EXCEL12_MAX_STRING_CODE_UNITS,
216        max_array_elements: 65_536,
217        max_total_bytes: 16 * 1024 * 1024,
218        max_allocations: 65_538,
219        max_depth: 8,
220    };
221}
222
223impl Default for ReturnLimits {
224    fn default() -> Self {
225        Self::DEFAULT
226    }
227}
228
229/// Future ownership mechanism selected for the planned return.
230#[derive(Clone, Copy, Debug, Eq, PartialEq)]
231pub enum ReturnOwnershipStrategy {
232    /// Rust owns stable storage until it transfers the root to Excel with `xlbitDLLFree`.
233    DllOwnedXloper12,
234}
235
236/// Exact future ABI storage totals for the chosen Prompt 05 layout.
237///
238/// `total_bytes` is exactly the sum of initialized ABI root, array-element,
239/// and counted-string storage. It excludes Rust container headers and allocator
240/// bookkeeping, which are allocator-dependent and are not claimed as heap cost.
241#[derive(Clone, Copy, Debug, Eq, PartialEq)]
242pub struct ReturnStorageTotals {
243    /// Bytes for the root `XLOPER12`.
244    pub root_bytes: usize,
245    /// Bytes for `xltypeMulti` element roots.
246    pub array_element_bytes: usize,
247    /// Total string payload UTF-16 code units.
248    pub string_payload_code_units: usize,
249    /// Total counted-string allocation code units, including prefixes.
250    pub string_storage_code_units: usize,
251    /// Bytes occupied by all counted-string allocations.
252    pub string_storage_bytes: usize,
253    /// Sum of ABI storage, excluding Rust allocator bookkeeping.
254    pub total_bytes: usize,
255    /// Number of backing allocations selected by the plan.
256    pub allocation_count: usize,
257}
258
259/// Immutable, fully validated description of a future return allocation.
260#[derive(Clone, Debug, PartialEq)]
261pub struct ReturnPlan {
262    pub(crate) root: PlannedValue,
263    pub(crate) totals: ReturnStorageTotals,
264    pub(crate) strategy: ReturnOwnershipStrategy,
265}
266
267impl ReturnPlan {
268    /// Returns the validated logical root; no raw ABI pointer exists yet.
269    pub const fn root(&self) -> &PlannedValue {
270        &self.root
271    }
272
273    /// Returns exact ABI storage accounting for later materialization.
274    pub const fn totals(&self) -> &ReturnStorageTotals {
275        &self.totals
276    }
277
278    /// Returns the ownership transfer strategy selected by this plan.
279    pub const fn strategy(&self) -> ReturnOwnershipStrategy {
280        self.strategy
281    }
282}
283
284/// Validated logical root retained by a [`ReturnPlan`].
285#[derive(Clone, Debug, PartialEq)]
286pub enum PlannedValue {
287    /// Planned floating-point scalar.
288    Number(f64),
289    /// Planned 32-bit integer scalar.
290    Integer(i32),
291    /// Planned Boolean scalar.
292    Boolean(bool),
293    /// Planned controlled worksheet error.
294    Error(ExcelError),
295    /// Planned missing value.
296    Missing,
297    /// Planned empty value.
298    Empty,
299    /// Planned counted-string data.
300    Text(PlannedText),
301    /// Planned rectangular array data.
302    Array(PlannedArray),
303}
304
305/// Original text plus its exact future counted-string sizes.
306#[derive(Clone, Debug, Eq, PartialEq)]
307pub struct PlannedText {
308    pub(crate) source: ReturnText,
309    pub(crate) payload_code_units: usize,
310    pub(crate) storage_code_units: usize,
311}
312
313impl PlannedText {
314    /// Returns the original owned text source.
315    pub const fn source(&self) -> &ReturnText {
316        &self.source
317    }
318
319    /// Returns the planned UTF-16 payload length excluding the count prefix.
320    pub const fn payload_code_units(&self) -> usize {
321        self.payload_code_units
322    }
323
324    /// Returns the planned allocation length including the count prefix.
325    pub const fn storage_code_units(&self) -> usize {
326        self.storage_code_units
327    }
328}
329
330/// Validated flat array metadata and elements in row-major order.
331#[derive(Clone, Debug, PartialEq)]
332pub struct PlannedArray {
333    pub(crate) rows: usize,
334    pub(crate) columns: usize,
335    pub(crate) elements: Box<[PlannedArrayElement]>,
336}
337
338impl PlannedArray {
339    /// Returns the planned row count.
340    pub const fn rows(&self) -> usize {
341        self.rows
342    }
343
344    /// Returns the planned column count.
345    pub const fn columns(&self) -> usize {
346        self.columns
347    }
348
349    /// Returns the planned element count.
350    pub const fn len(&self) -> usize {
351        self.elements.len()
352    }
353
354    /// Returns whether the planned array has no elements.
355    pub const fn is_empty(&self) -> bool {
356        self.elements.is_empty()
357    }
358
359    /// Returns planned elements in flat row-major order.
360    pub fn elements(&self) -> &[PlannedArrayElement] {
361        &self.elements
362    }
363}
364
365/// Supported non-array value within a planned `xltypeMulti`.
366#[derive(Clone, Debug, PartialEq)]
367pub enum PlannedArrayElement {
368    /// Planned floating-point element.
369    Number(f64),
370    /// Planned integer element.
371    Integer(i32),
372    /// Planned Boolean element.
373    Boolean(bool),
374    /// Planned worksheet-error element.
375    Error(ExcelError),
376    /// Planned missing element.
377    Missing,
378    /// Planned empty element.
379    Empty,
380    /// Planned counted-string element.
381    Text(PlannedText),
382}
383
384struct Planner<'limits> {
385    limits: &'limits ReturnLimits,
386    array_element_bytes: usize,
387    string_payload_code_units: usize,
388    string_storage_code_units: usize,
389    string_storage_bytes: usize,
390    allocation_count: usize,
391}
392
393impl<'limits> Planner<'limits> {
394    fn new(limits: &'limits ReturnLimits) -> Self {
395        Self {
396            limits,
397            array_element_bytes: 0,
398            string_payload_code_units: 0,
399            string_storage_code_units: 0,
400            string_storage_bytes: 0,
401            allocation_count: 1,
402        }
403    }
404
405    fn plan(mut self, value: ExcelReturnValue) -> Result<ReturnPlan, ReturnError> {
406        self.enforce_depth(0)?;
407        let root = self.plan_root(value)?;
408        let total_bytes = XLOPER12_BYTES
409            .checked_add(self.array_element_bytes)
410            .and_then(|total| total.checked_add(self.string_storage_bytes))
411            .ok_or(ReturnError::TotalByteOverflow)?;
412        if total_bytes > self.limits.max_total_bytes {
413            return Err(ReturnError::TotalByteLimitExceeded {
414                required: total_bytes,
415                maximum: self.limits.max_total_bytes,
416            });
417        }
418        if self.allocation_count > self.limits.max_allocations {
419            return Err(ReturnError::AllocationCountLimitExceeded {
420                required: self.allocation_count,
421                maximum: self.limits.max_allocations,
422            });
423        }
424        Ok(ReturnPlan {
425            root,
426            totals: ReturnStorageTotals {
427                root_bytes: XLOPER12_BYTES,
428                array_element_bytes: self.array_element_bytes,
429                string_payload_code_units: self.string_payload_code_units,
430                string_storage_code_units: self.string_storage_code_units,
431                string_storage_bytes: self.string_storage_bytes,
432                total_bytes,
433                allocation_count: self.allocation_count,
434            },
435            strategy: ReturnOwnershipStrategy::DllOwnedXloper12,
436        })
437    }
438
439    fn plan_root(&mut self, value: ExcelReturnValue) -> Result<PlannedValue, ReturnError> {
440        Ok(match value {
441            ExcelReturnValue::Number(value) => PlannedValue::Number(value),
442            ExcelReturnValue::Integer(value) => PlannedValue::Integer(value),
443            ExcelReturnValue::Boolean(value) => PlannedValue::Boolean(value),
444            ExcelReturnValue::Error(value) => PlannedValue::Error(value),
445            ExcelReturnValue::Missing => PlannedValue::Missing,
446            ExcelReturnValue::Empty => PlannedValue::Empty,
447            ExcelReturnValue::Text(value) => PlannedValue::Text(self.plan_text(value)?),
448            ExcelReturnValue::Array(value) => PlannedValue::Array(self.plan_array(value)?),
449        })
450    }
451
452    fn plan_array(&mut self, array: ExcelReturnArray) -> Result<PlannedArray, ReturnError> {
453        self.enforce_depth(1)?;
454        let count = array.rows.checked_mul(array.columns).ok_or(
455            ReturnError::ArrayElementCountOverflow {
456                rows: array.rows,
457                columns: array.columns,
458            },
459        )?;
460        if count != array.values.len() {
461            return Err(ReturnError::InvalidArrayShape {
462                rows: array.rows,
463                columns: array.columns,
464                elements: array.values.len(),
465            });
466        }
467        if array.rows > excel_api_sys::EXCEL12_MAX_ROWS as usize
468            || array.columns > excel_api_sys::EXCEL12_MAX_COLUMNS as usize
469        {
470            return Err(ReturnError::ArrayDimensionExceedsAbi {
471                rows: array.rows,
472                columns: array.columns,
473            });
474        }
475        if array.rows == 0 || array.columns == 0 {
476            return Err(ReturnError::EmptyArrayUnsupported);
477        }
478        if count > self.limits.max_array_elements {
479            return Err(ReturnError::ArrayElementLimitExceeded {
480                actual: count,
481                maximum: self.limits.max_array_elements,
482            });
483        }
484        self.array_element_bytes = count
485            .checked_mul(XLOPER12_BYTES)
486            .ok_or(ReturnError::TotalByteOverflow)?;
487        self.add_allocation()?;
488
489        let mut elements = Vec::with_capacity(count);
490        for value in array.values.into_vec() {
491            elements.push(self.plan_array_element(value)?);
492        }
493        Ok(PlannedArray {
494            rows: array.rows,
495            columns: array.columns,
496            elements: elements.into_boxed_slice(),
497        })
498    }
499
500    fn plan_array_element(
501        &mut self,
502        value: ExcelReturnValue,
503    ) -> Result<PlannedArrayElement, ReturnError> {
504        Ok(match value {
505            ExcelReturnValue::Number(value) => PlannedArrayElement::Number(value),
506            ExcelReturnValue::Integer(value) => PlannedArrayElement::Integer(value),
507            ExcelReturnValue::Boolean(value) => PlannedArrayElement::Boolean(value),
508            ExcelReturnValue::Error(value) => PlannedArrayElement::Error(value),
509            ExcelReturnValue::Missing => PlannedArrayElement::Missing,
510            ExcelReturnValue::Empty => PlannedArrayElement::Empty,
511            ExcelReturnValue::Text(value) => PlannedArrayElement::Text(self.plan_text(value)?),
512            ExcelReturnValue::Array(_) => return Err(ReturnError::NestedArrayUnsupported),
513        })
514    }
515
516    fn plan_text(&mut self, source: ReturnText) -> Result<PlannedText, ReturnError> {
517        let payload_code_units = match &source {
518            ReturnText::Utf8(value) => value.encode_utf16().count(),
519            ReturnText::Utf16(value) => value.len_utf16(),
520        };
521        if payload_code_units > excel_api_sys::EXCEL12_MAX_STRING_CODE_UNITS {
522            return Err(ReturnError::StringTooLongForExcel {
523                actual: payload_code_units,
524                maximum: excel_api_sys::EXCEL12_MAX_STRING_CODE_UNITS,
525            });
526        }
527        if payload_code_units > self.limits.max_string_code_units {
528            return Err(ReturnError::StringLimitExceeded {
529                actual: payload_code_units,
530                maximum: self.limits.max_string_code_units,
531            });
532        }
533        let storage_code_units = payload_code_units
534            .checked_add(1)
535            .ok_or(ReturnError::TotalByteOverflow)?;
536        let storage_bytes = storage_code_units
537            .checked_mul(XCHAR_BYTES)
538            .ok_or(ReturnError::TotalByteOverflow)?;
539        self.string_payload_code_units = self
540            .string_payload_code_units
541            .checked_add(payload_code_units)
542            .ok_or(ReturnError::TotalByteOverflow)?;
543        self.string_storage_code_units = self
544            .string_storage_code_units
545            .checked_add(storage_code_units)
546            .ok_or(ReturnError::TotalByteOverflow)?;
547        self.string_storage_bytes = self
548            .string_storage_bytes
549            .checked_add(storage_bytes)
550            .ok_or(ReturnError::TotalByteOverflow)?;
551        self.add_allocation()?;
552        Ok(PlannedText {
553            source,
554            payload_code_units,
555            storage_code_units,
556        })
557    }
558
559    fn add_allocation(&mut self) -> Result<(), ReturnError> {
560        self.allocation_count = self
561            .allocation_count
562            .checked_add(1)
563            .ok_or(ReturnError::AllocationCountOverflow)?;
564        Ok(())
565    }
566
567    fn enforce_depth(&self, depth: usize) -> Result<(), ReturnError> {
568        if depth > self.limits.max_depth {
569            return Err(ReturnError::PlanningDepthExceeded {
570                depth,
571                maximum: self.limits.max_depth,
572            });
573        }
574        Ok(())
575    }
576}
577
578#[cfg(test)]
579mod tests {
580    use super::*;
581
582    fn scalar_totals() -> ReturnStorageTotals {
583        ReturnStorageTotals {
584            root_bytes: XLOPER12_BYTES,
585            array_element_bytes: 0,
586            string_payload_code_units: 0,
587            string_storage_code_units: 0,
588            string_storage_bytes: 0,
589            total_bytes: XLOPER12_BYTES,
590            allocation_count: 1,
591        }
592    }
593
594    #[test]
595    fn every_scalar_and_excel_error_plans_as_one_root() {
596        let scalars = [
597            ExcelReturnValue::Number(1.25),
598            ExcelReturnValue::Integer(-7),
599            ExcelReturnValue::Boolean(true),
600            ExcelReturnValue::Missing,
601            ExcelReturnValue::Empty,
602        ];
603        for value in scalars {
604            let plan = value.plan().unwrap();
605            assert_eq!(*plan.totals(), scalar_totals());
606            assert_eq!(plan.strategy(), ReturnOwnershipStrategy::DllOwnedXloper12);
607        }
608
609        for error in [
610            ExcelError::Null,
611            ExcelError::Div0,
612            ExcelError::Value,
613            ExcelError::Ref,
614            ExcelError::Name,
615            ExcelError::Num,
616            ExcelError::Na,
617            ExcelError::GettingData,
618        ] {
619            let plan = ExcelReturnValue::Error(error).plan().unwrap();
620            assert_eq!(plan.root(), &PlannedValue::Error(error));
621            assert_eq!(*plan.totals(), scalar_totals());
622        }
623    }
624
625    #[test]
626    fn strings_preserve_sources_and_account_for_prefix_exactly() {
627        let cases = [
628            ReturnText::from(""),
629            ReturnText::from("ASCII"),
630            ReturnText::from("é水"),
631            ReturnText::from("😃"),
632            ReturnText::from("A\0B"),
633            ReturnText::Utf16(ExcelString::from_utf16_units([0xD83D, 0xDE03])),
634            ReturnText::Utf16(ExcelString::from_utf16_units([0xD800])),
635            ReturnText::Utf16(ExcelString::from_utf16_units([0xDC00])),
636        ];
637        for source in cases {
638            let expected_units = match &source {
639                ReturnText::Utf8(value) => value.encode_utf16().count(),
640                ReturnText::Utf16(value) => value.len_utf16(),
641            };
642            let plan = ExcelReturnValue::Text(source.clone()).plan().unwrap();
643            let PlannedValue::Text(text) = plan.root() else {
644                panic!("expected planned text");
645            };
646            assert_eq!(text.source(), &source);
647            assert_eq!(text.payload_code_units(), expected_units);
648            assert_eq!(text.storage_code_units(), expected_units + 1);
649            assert_eq!(plan.totals().string_payload_code_units, expected_units);
650            assert_eq!(plan.totals().string_storage_code_units, expected_units + 1);
651            assert_eq!(plan.totals().string_storage_bytes, (expected_units + 1) * 2);
652            assert_eq!(
653                plan.totals().total_bytes,
654                XLOPER12_BYTES + (expected_units + 1) * 2
655            );
656            assert_eq!(plan.totals().allocation_count, 2);
657        }
658
659        let utf8 = "A😃";
660        assert_ne!(utf8.len(), utf8.encode_utf16().count());
661        let plan = ExcelReturnValue::Text(utf8.into()).plan().unwrap();
662        assert_eq!(plan.totals().string_payload_code_units, 3);
663    }
664
665    #[test]
666    fn excel_string_maximum_is_a_hard_boundary() {
667        let maximum = excel_api_sys::EXCEL12_MAX_STRING_CODE_UNITS;
668        let accepted = ExcelString::from_utf16_units(vec![0xD800; maximum]);
669        let plan = ExcelReturnValue::Text(accepted.into()).plan().unwrap();
670        assert_eq!(plan.totals().string_payload_code_units, maximum);
671
672        let rejected = ExcelString::from_utf16_units(vec![0_u16; maximum + 1]);
673        assert_eq!(
674            ExcelReturnValue::Text(rejected.into()).plan(),
675            Err(ReturnError::StringTooLongForExcel {
676                actual: maximum + 1,
677                maximum,
678            })
679        );
680    }
681
682    #[test]
683    fn rectangular_array_preserves_order_variants_and_exact_storage() {
684        let single = ExcelReturnArray::new(1, 1, vec![ExcelReturnValue::Integer(9)]).unwrap();
685        let single = ExcelReturnValue::Array(single).plan().unwrap();
686        let PlannedValue::Array(single) = single.root() else {
687            panic!("expected planned array");
688        };
689        assert_eq!((single.rows(), single.columns(), single.len()), (1, 1, 1));
690
691        let values = vec![
692            ExcelReturnValue::Number(1.0),
693            ExcelReturnValue::Integer(2),
694            ExcelReturnValue::Text(ReturnText::from("A")),
695            ExcelReturnValue::Error(ExcelError::Na),
696            ExcelReturnValue::Boolean(false),
697            ExcelReturnValue::Empty,
698        ];
699        let array = ExcelReturnArray::new(2, 3, values).unwrap();
700        let plan = ExcelReturnValue::Array(array).plan().unwrap();
701        let PlannedValue::Array(array) = plan.root() else {
702            panic!("expected planned array");
703        };
704        assert_eq!((array.rows(), array.columns(), array.len()), (2, 3, 6));
705        assert!(matches!(
706            array.elements()[0],
707            PlannedArrayElement::Number(1.0)
708        ));
709        assert!(matches!(
710            array.elements()[1],
711            PlannedArrayElement::Integer(2)
712        ));
713        assert!(matches!(array.elements()[2], PlannedArrayElement::Text(_)));
714        assert!(matches!(
715            array.elements()[3],
716            PlannedArrayElement::Error(ExcelError::Na)
717        ));
718        assert!(matches!(
719            array.elements()[4],
720            PlannedArrayElement::Boolean(false)
721        ));
722        assert!(matches!(array.elements()[5], PlannedArrayElement::Empty));
723        assert_eq!(plan.totals().array_element_bytes, 6 * XLOPER12_BYTES);
724        assert_eq!(plan.totals().string_payload_code_units, 1);
725        assert_eq!(plan.totals().string_storage_bytes, 4);
726        assert_eq!(
727            plan.totals().total_bytes,
728            XLOPER12_BYTES + 6 * XLOPER12_BYTES + 4
729        );
730        assert_eq!(plan.totals().allocation_count, 3);
731    }
732
733    #[test]
734    fn array_shape_dimension_empty_and_nesting_fail_precisely() {
735        assert!(matches!(
736            ExcelReturnArray::new(usize::MAX, 2, Vec::<ExcelReturnValue>::new()),
737            Err(ReturnError::ArrayElementCountOverflow { .. })
738        ));
739        assert!(matches!(
740            ExcelReturnArray::new(2, 2, vec![ExcelReturnValue::Empty]),
741            Err(ReturnError::InvalidArrayShape { .. })
742        ));
743
744        let empty = ExcelReturnArray::new(0, 0, Vec::new()).unwrap();
745        assert_eq!(
746            ExcelReturnValue::Array(empty).plan(),
747            Err(ReturnError::EmptyArrayUnsupported)
748        );
749
750        let dimension_overflow = ExcelReturnArray {
751            rows: excel_api_sys::EXCEL12_MAX_ROWS as usize + 1,
752            columns: 1,
753            values: Vec::new().into_boxed_slice(),
754        };
755        assert!(matches!(
756            ExcelReturnValue::Array(dimension_overflow).plan(),
757            Err(ReturnError::InvalidArrayShape { .. })
758        ));
759
760        let inner = ExcelReturnArray::new(1, 1, vec![ExcelReturnValue::Empty]).unwrap();
761        let outer = ExcelReturnArray::new(1, 1, vec![ExcelReturnValue::Array(inner)]).unwrap();
762        assert_eq!(
763            ExcelReturnValue::Array(outer).plan(),
764            Err(ReturnError::NestedArrayUnsupported)
765        );
766    }
767
768    #[test]
769    fn dimension_overflow_is_checked_before_project_element_limit() {
770        let rows = excel_api_sys::EXCEL12_MAX_ROWS as usize + 1;
771        let array = ExcelReturnArray {
772            rows,
773            columns: 0,
774            values: Vec::new().into_boxed_slice(),
775        };
776        assert_eq!(
777            ExcelReturnValue::Array(array).plan(),
778            Err(ReturnError::ArrayDimensionExceedsAbi { rows, columns: 0 })
779        );
780    }
781
782    #[test]
783    fn return_limits_accept_boundaries_and_reject_one_over() {
784        let limits = ReturnLimits {
785            max_string_code_units: 2,
786            max_array_elements: 2,
787            max_total_bytes: usize::MAX,
788            max_allocations: 3,
789            max_depth: 8,
790        };
791        ExcelReturnValue::Text(ReturnText::from("ab"))
792            .plan_with_limits(&limits)
793            .unwrap();
794        assert_eq!(
795            ExcelReturnValue::Text(ReturnText::from("abc")).plan_with_limits(&limits),
796            Err(ReturnError::StringLimitExceeded {
797                actual: 3,
798                maximum: 2,
799            })
800        );
801
802        let two =
803            ExcelReturnArray::new(1, 2, vec![ExcelReturnValue::Empty, ExcelReturnValue::Empty])
804                .unwrap();
805        ExcelReturnValue::Array(two)
806            .plan_with_limits(&limits)
807            .unwrap();
808        let three = ExcelReturnArray::new(1, 3, vec![ExcelReturnValue::Empty; 3]).unwrap();
809        assert_eq!(
810            ExcelReturnValue::Array(three).plan_with_limits(&limits),
811            Err(ReturnError::ArrayElementLimitExceeded {
812                actual: 3,
813                maximum: 2,
814            })
815        );
816
817        let exact_bytes = ReturnLimits {
818            max_total_bytes: XLOPER12_BYTES,
819            ..ReturnLimits::default()
820        };
821        ExcelReturnValue::Empty
822            .plan_with_limits(&exact_bytes)
823            .unwrap();
824        let one_under = ReturnLimits {
825            max_total_bytes: XLOPER12_BYTES - 1,
826            ..ReturnLimits::default()
827        };
828        assert_eq!(
829            ExcelReturnValue::Empty.plan_with_limits(&one_under),
830            Err(ReturnError::TotalByteLimitExceeded {
831                required: XLOPER12_BYTES,
832                maximum: XLOPER12_BYTES - 1,
833            })
834        );
835    }
836
837    #[test]
838    fn aggregate_strings_allocation_and_depth_limits_are_enforced() {
839        let array = ExcelReturnArray::new(
840            1,
841            2,
842            vec![
843                ExcelReturnValue::Text(ReturnText::from("A")),
844                ExcelReturnValue::Text(ReturnText::Utf16(ExcelString::from_utf16_units([0xD800]))),
845            ],
846        )
847        .unwrap();
848        let plan = ExcelReturnValue::Array(array.clone()).plan().unwrap();
849        assert_eq!(plan.totals().string_payload_code_units, 2);
850        assert_eq!(plan.totals().string_storage_code_units, 4);
851        assert_eq!(plan.totals().allocation_count, 4);
852
853        let exact_allocation_limit = ReturnLimits {
854            max_allocations: 4,
855            ..ReturnLimits::default()
856        };
857        ExcelReturnValue::Array(array.clone())
858            .plan_with_limits(&exact_allocation_limit)
859            .unwrap();
860
861        let allocation_limit = ReturnLimits {
862            max_allocations: 3,
863            ..ReturnLimits::default()
864        };
865        assert_eq!(
866            ExcelReturnValue::Array(array.clone()).plan_with_limits(&allocation_limit),
867            Err(ReturnError::AllocationCountLimitExceeded {
868                required: 4,
869                maximum: 3,
870            })
871        );
872
873        let byte_limit = ReturnLimits {
874            max_total_bytes: plan.totals().total_bytes - 1,
875            ..ReturnLimits::default()
876        };
877        assert!(matches!(
878            ExcelReturnValue::Array(array.clone()).plan_with_limits(&byte_limit),
879            Err(ReturnError::TotalByteLimitExceeded { .. })
880        ));
881
882        let depth_limit = ReturnLimits {
883            max_depth: 0,
884            ..ReturnLimits::default()
885        };
886        assert_eq!(
887            ExcelReturnValue::Array(array).plan_with_limits(&depth_limit),
888            Err(ReturnError::PlanningDepthExceeded {
889                depth: 1,
890                maximum: 0,
891            })
892        );
893    }
894
895    #[test]
896    fn accounting_overflow_paths_are_explicit() {
897        let limits = ReturnLimits {
898            max_total_bytes: usize::MAX,
899            max_allocations: usize::MAX,
900            ..ReturnLimits::default()
901        };
902        let planner = Planner {
903            limits: &limits,
904            array_element_bytes: usize::MAX,
905            string_payload_code_units: 0,
906            string_storage_code_units: 0,
907            string_storage_bytes: 0,
908            allocation_count: 1,
909        };
910        assert_eq!(
911            planner.plan(ExcelReturnValue::Empty),
912            Err(ReturnError::TotalByteOverflow)
913        );
914
915        let mut planner = Planner {
916            limits: &limits,
917            array_element_bytes: 0,
918            string_payload_code_units: 0,
919            string_storage_code_units: 0,
920            string_storage_bytes: 0,
921            allocation_count: usize::MAX,
922        };
923        assert_eq!(
924            planner.add_allocation(),
925            Err(ReturnError::AllocationCountOverflow)
926        );
927    }
928
929    #[test]
930    fn planning_is_deterministic_owned_send_sync_and_pointer_free() {
931        fn assert_owned<T: Send + Sync + 'static>() {}
932        assert_owned::<ReturnText>();
933        assert_owned::<ExcelReturnValue>();
934        assert_owned::<ReturnPlan>();
935
936        let value = ExcelReturnValue::Array(
937            ExcelReturnArray::new(
938                1,
939                2,
940                vec![
941                    ExcelReturnValue::Integer(7),
942                    ExcelReturnValue::Text(ReturnText::Utf16(ExcelString::from_utf16_units([
943                        0xD800, 0, 0xDC00,
944                    ]))),
945                ],
946            )
947            .unwrap(),
948        );
949        let first = value.clone().plan().unwrap();
950        let second = value.plan().unwrap();
951        assert_eq!(first, second);
952
953        let PlannedValue::Array(array) = first.root() else {
954            panic!("expected array");
955        };
956        let PlannedArrayElement::Text(text) = &array.elements()[1] else {
957            panic!("expected text");
958        };
959        let ReturnText::Utf16(text) = text.source() else {
960            panic!("expected original UTF-16 source");
961        };
962        assert_eq!(text.as_utf16(), &[0xD800, 0, 0xDC00]);
963
964        // Public planned fields are owned enums, integers, and slices; no API
965        // exposes an Excel ABI pointer or a callback lifetime.
966        let moved = std::thread::spawn(move || first.totals().total_bytes)
967            .join()
968            .unwrap();
969        assert!(moved >= XLOPER12_BYTES);
970    }
971
972    #[test]
973    fn semantic_values_convert_without_losing_integer_or_utf16_identity() {
974        let semantic = ExcelValue::Array(
975            ExcelArray::new(
976                1,
977                2,
978                vec![
979                    ExcelValue::Integer(12),
980                    ExcelValue::Text(ExcelString::from_utf16_units([0xD800])),
981                ],
982            )
983            .unwrap(),
984        );
985        let plan = ExcelReturnValue::from(semantic).plan().unwrap();
986        let PlannedValue::Array(array) = plan.root() else {
987            panic!("expected array");
988        };
989        assert!(matches!(
990            array.elements()[0],
991            PlannedArrayElement::Integer(12)
992        ));
993        let PlannedArrayElement::Text(text) = &array.elements()[1] else {
994            panic!("expected text");
995        };
996        assert!(matches!(text.source(), ReturnText::Utf16(_)));
997    }
998}