Skip to main content

excel_api/
value.rs

1use core::slice;
2
3use crate::{ExcelError, ExcelStr, OwnedValueError, Utf16ConversionError};
4
5/// Owned UTF-16 payload independent of Excel callback memory.
6///
7/// The box contains payload code units only: no Excel length prefix and no
8/// trailing NUL requirement. Arbitrary UTF-16 code units are preserved.
9#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
10pub struct ExcelString {
11    units: Box<[u16]>,
12}
13
14impl ExcelString {
15    /// Owns the supplied UTF-16 code units without validating Unicode scalar
16    /// values. Conversion limits apply when callback memory is copied, not to
17    /// semantic strings constructed directly by Rust callers.
18    pub fn from_utf16_units(units: impl Into<Box<[u16]>>) -> Self {
19        Self {
20            units: units.into(),
21        }
22    }
23
24    /// Encodes valid UTF-8 as owned UTF-16 code units.
25    pub fn from_utf8(value: &str) -> Self {
26        Self::from_utf16_units(value.encode_utf16().collect::<Vec<_>>())
27    }
28
29    /// Returns the exact owned UTF-16 code units, including embedded NULs.
30    pub fn as_utf16(&self) -> &[u16] {
31        &self.units
32    }
33
34    /// Returns the number of UTF-16 code units, not Unicode scalar values.
35    pub const fn len_utf16(&self) -> usize {
36        self.units.len()
37    }
38
39    /// Reports whether the string has no UTF-16 payload units.
40    pub const fn is_empty(&self) -> bool {
41        self.units.is_empty()
42    }
43
44    /// Strictly decodes the UTF-16 payload.
45    pub fn to_string(&self) -> Result<String, Utf16ConversionError> {
46        String::from_utf16(&self.units).map_err(|_| Utf16ConversionError)
47    }
48
49    /// Explicitly decodes the payload, replacing unpaired surrogates with the
50    /// Unicode replacement character.
51    pub fn to_string_lossy(&self) -> String {
52        String::from_utf16_lossy(&self.units)
53    }
54}
55
56impl From<&str> for ExcelString {
57    fn from(value: &str) -> Self {
58        Self::from_utf8(value)
59    }
60}
61
62impl From<String> for ExcelString {
63    fn from(value: String) -> Self {
64        Self::from_utf8(&value)
65    }
66}
67
68impl From<ExcelStr<'_>> for ExcelString {
69    fn from(value: ExcelStr<'_>) -> Self {
70        Self::from_utf16_units(Box::<[u16]>::from(value.as_utf16()))
71    }
72}
73
74impl TryFrom<&ExcelString> for String {
75    type Error = Utf16ConversionError;
76
77    fn try_from(value: &ExcelString) -> Result<Self, Self::Error> {
78        value.to_string()
79    }
80}
81
82/// Ordinary owned Rust representation of an Excel value.
83///
84/// Every variant is independent of callback storage. References deliberately
85/// remain outside this semantic value model until an owned-reference contract
86/// is specified.
87#[derive(Clone, Debug, PartialEq)]
88pub enum ExcelValue {
89    /// An IEEE-754 worksheet number.
90    Number(f64),
91    /// An Excel integer represented as an `i32`.
92    Integer(i32),
93    /// An Excel Boolean.
94    Boolean(bool),
95    /// A controlled Excel worksheet error.
96    Error(ExcelError),
97    /// An omitted Excel argument.
98    Missing,
99    /// An empty Excel value.
100    Empty,
101    /// Owned UTF-16 text.
102    Text(ExcelString),
103    /// An owned rectangular array.
104    Array(ExcelArray),
105}
106
107impl ExcelValue {
108    /// Returns the stable diagnostic name of this semantic variant.
109    pub const fn kind_name(&self) -> &'static str {
110        match self {
111            Self::Number(_) => "number",
112            Self::Integer(_) => "integer",
113            Self::Boolean(_) => "boolean",
114            Self::Error(_) => "error",
115            Self::Missing => "missing",
116            Self::Empty => "empty",
117            Self::Text(_) => "text",
118            Self::Array(_) => "array",
119        }
120    }
121}
122
123/// Owned immutable rectangular array in row-major order.
124#[derive(Clone, Debug, PartialEq)]
125pub struct ExcelArray {
126    rows: usize,
127    columns: usize,
128    values: Box<[ExcelValue]>,
129}
130
131impl ExcelArray {
132    /// Creates a rectangular row-major array.
133    ///
134    /// Returns an error when `rows * columns` overflows, the element count does
135    /// not match the shape, or an element is itself an array.
136    pub fn new(
137        rows: usize,
138        columns: usize,
139        values: impl Into<Box<[ExcelValue]>>,
140    ) -> Result<Self, OwnedValueError> {
141        let values = values.into();
142        let expected = rows
143            .checked_mul(columns)
144            .ok_or(OwnedValueError::ArrayShapeOverflow { rows, columns })?;
145        if values.len() != expected {
146            return Err(OwnedValueError::InvalidArrayShape {
147                rows,
148                columns,
149                elements: values.len(),
150            });
151        }
152        if values
153            .iter()
154            .any(|value| matches!(value, ExcelValue::Array(_)))
155        {
156            return Err(OwnedValueError::NestedArrayUnsupported);
157        }
158
159        Ok(Self {
160            rows,
161            columns,
162            values,
163        })
164    }
165
166    /// Returns the number of rows.
167    pub const fn rows(&self) -> usize {
168        self.rows
169    }
170
171    /// Returns the number of columns.
172    pub const fn columns(&self) -> usize {
173        self.columns
174    }
175
176    /// Returns the total row-major element count.
177    pub const fn len(&self) -> usize {
178        self.values.len()
179    }
180
181    /// Reports whether the array contains no elements.
182    pub const fn is_empty(&self) -> bool {
183        self.values.is_empty()
184    }
185
186    /// Returns all values in row-major order.
187    pub fn values(&self) -> &[ExcelValue] {
188        &self.values
189    }
190
191    /// Returns the value at a zero-based row and column, if in bounds.
192    pub fn get(&self, row: usize, column: usize) -> Option<&ExcelValue> {
193        if row >= self.rows || column >= self.columns {
194            return None;
195        }
196        self.values.get(row * self.columns + column)
197    }
198
199    /// Returns one zero-based row as a contiguous row-major slice.
200    pub fn row(&self, row: usize) -> Option<&[ExcelValue]> {
201        if row >= self.rows {
202            return None;
203        }
204        let start = row * self.columns;
205        self.values.get(start..start + self.columns)
206    }
207
208    /// Returns an iterator over one zero-based column, if in bounds.
209    pub fn column(&self, column: usize) -> Option<ExcelArrayColumn<'_>> {
210        (column < self.columns).then_some(ExcelArrayColumn {
211            array: self,
212            column,
213            next_row: 0,
214        })
215    }
216
217    /// Iterates all values in row-major order.
218    pub fn iter(&self) -> slice::Iter<'_, ExcelValue> {
219        self.values.iter()
220    }
221
222    pub(crate) fn into_parts(self) -> (usize, usize, Box<[ExcelValue]>) {
223        (self.rows, self.columns, self.values)
224    }
225}
226
227/// Checked iterator over one column of an owned rectangular array.
228#[derive(Debug)]
229pub struct ExcelArrayColumn<'array> {
230    array: &'array ExcelArray,
231    column: usize,
232    next_row: usize,
233}
234
235impl<'array> Iterator for ExcelArrayColumn<'array> {
236    type Item = &'array ExcelValue;
237
238    fn next(&mut self) -> Option<Self::Item> {
239        let row = self.next_row;
240        let value = self.array.get(row, self.column)?;
241        self.next_row += 1;
242        Some(value)
243    }
244
245    fn size_hint(&self) -> (usize, Option<usize>) {
246        let remaining = self.array.rows - self.next_row;
247        (remaining, Some(remaining))
248    }
249}
250
251impl ExactSizeIterator for ExcelArrayColumn<'_> {}
252
253/// Exact optional-value semantics for callers that must distinguish omitted
254/// arguments from blank cells.
255#[derive(Clone, Debug, PartialEq)]
256pub enum OptionalValue<T> {
257    /// An omitted argument.
258    Missing,
259    /// An empty Excel value.
260    Empty,
261    /// A present converted value.
262    Value(T),
263}
264
265#[cfg(test)]
266mod tests {
267    use super::*;
268
269    #[test]
270    fn excel_string_preserves_every_required_utf16_form() {
271        let cases: &[&[u16]] = &[
272            &[],
273            &[b'A' as u16],
274            &[0x00E9, 0x6C34],
275            &[0xD83D, 0xDE03],
276            &[0xD800],
277            &[0xDC00],
278            &[b'A' as u16, 0, b'B' as u16],
279        ];
280        for units in cases {
281            let value = ExcelString::from_utf16_units(units.to_vec());
282            assert_eq!(value.as_utf16(), *units);
283            assert_eq!(value.len_utf16(), units.len());
284            assert_eq!(value.is_empty(), units.is_empty());
285        }
286    }
287
288    #[test]
289    fn strict_and_lossy_utf16_conversion_are_distinct() {
290        let valid = ExcelString::from_utf16_units([0xD83D, 0xDE03].to_vec());
291        assert_eq!(valid.to_string().as_deref(), Ok("😃"));
292
293        let invalid = ExcelString::from_utf16_units([0xD800].to_vec());
294        assert_eq!(invalid.to_string(), Err(Utf16ConversionError));
295        assert_eq!(invalid.to_string_lossy(), "�");
296
297        let invalid = ExcelString::from_utf16_units([0xDC00].to_vec());
298        assert_eq!(invalid.to_string(), Err(Utf16ConversionError));
299        assert_eq!(invalid.to_string_lossy(), "�");
300    }
301
302    #[test]
303    fn utf8_conversion_is_infallible_and_exact() {
304        let value = ExcelString::from("Aé水😃");
305        assert_eq!(value.to_string().as_deref(), Ok("Aé水😃"));
306
307        let value = ExcelString::from(String::from("owned 😃"));
308        assert_eq!(String::try_from(&value).as_deref(), Ok("owned 😃"));
309    }
310
311    #[test]
312    fn array_shape_and_nested_array_are_rejected() {
313        assert!(matches!(
314            ExcelArray::new(2, 2, vec![ExcelValue::Number(1.0)]),
315            Err(OwnedValueError::InvalidArrayShape { .. })
316        ));
317        assert!(matches!(
318            ExcelArray::new(usize::MAX, 2, Vec::<ExcelValue>::new()),
319            Err(OwnedValueError::ArrayShapeOverflow { .. })
320        ));
321
322        let inner = ExcelArray::new(0, 0, Vec::<ExcelValue>::new()).unwrap();
323        assert!(inner.is_empty());
324        assert_eq!(
325            ExcelArray::new(1, 1, vec![ExcelValue::Array(inner)]),
326            Err(OwnedValueError::NestedArrayUnsupported)
327        );
328    }
329
330    #[test]
331    fn array_indexing_rows_columns_and_iteration_are_row_major() {
332        let array =
333            ExcelArray::new(2, 3, (0..6).map(ExcelValue::Integer).collect::<Vec<_>>()).unwrap();
334
335        assert_eq!(array.len(), 6);
336        assert!(!array.is_empty());
337        assert_eq!(array.get(1, 1), Some(&ExcelValue::Integer(4)));
338        assert_eq!(array.get(2, 0), None);
339        assert_eq!(
340            array.row(1),
341            Some(
342                [
343                    ExcelValue::Integer(3),
344                    ExcelValue::Integer(4),
345                    ExcelValue::Integer(5),
346                ]
347                .as_slice()
348            )
349        );
350        assert_eq!(
351            array.column(1).unwrap().collect::<Vec<_>>(),
352            vec![&ExcelValue::Integer(1), &ExcelValue::Integer(4)]
353        );
354        assert_eq!(array.iter().count(), 6);
355    }
356
357    #[test]
358    fn owned_types_are_static_send_and_sync() {
359        fn assert_owned<T: Send + Sync + 'static>() {}
360        assert_owned::<ExcelString>();
361        assert_owned::<ExcelValue>();
362        assert_owned::<ExcelArray>();
363
364        let value = ExcelValue::Text(ExcelString::from("worker"));
365        let returned = std::thread::spawn(move || value).join().unwrap();
366        assert_eq!(
367            returned,
368            ExcelValue::Text(ExcelString::from_utf16_units(
369                "worker".encode_utf16().collect::<Vec<_>>()
370            ))
371        );
372    }
373}