Skip to main content

unityrs_meshdecode/
unpack.rs

1// Ported from UnityPy 1.25.2 (MIT): UnityPyBoost/Mesh.cpp's unpack_vertexdata (the C++ extension shipped in UnityPy 1.25.2), and the struct.iter_unpack of helpers/MeshHelper.py's read_vertex_data. See THIRD_PARTY_LICENSES.
2//! The strided gather: one channel's components out of the vertex data,
3//! as UnityPyBoost copies them (`unpack_vertexdata`,
4//! `UnityPyBoost/Mesh.cpp:23-210`), then unpacked as `read_vertex_data`
5//! unpacks them (`struct.iter_unpack`, `helpers/MeshHelper.py:392`).
6//!
7//! **UnityPyBoost's arithmetic.** The arguments are C `uint32_t`s (Python's
8//! `I` format masks an `int` to its low 32 bits, `UnityPyBoost/Mesh.cpp:36`),
9//! and every offset is computed in them, so it wraps. Its one check is the
10//! largest offset read, computed so (`:50-56`), against the data's length:
11//! past it, `ValueError` "Vertex data access out of bounds"
12//! ([`MeshError::OutOfBounds`]). Within it, the copy (`:66-75`) reads each
13//! component at its own wrapped offset, and its output buffer is the
14//! wrapped product of the count, the dimension and the component's size
15//! (`:47`). Where nothing wraps that is a plain gather, and this is it,
16//! exactly. Where the check passes but a component's wrapped offset lies
17//! past the data, or the product wraps, UnityPyBoost reads or writes
18//! outside its buffers, undefined behaviour: [`MeshError::WrappedAccess`]
19//! refuses it before any output is returned (`PARITY.md` section 19.3): a
20//! wrapped product before anything is read, a component past the data when
21//! the gather reaches it, the components before it read into the output
22//! that is then dropped. A stride that wraps to a step backwards
23//! (`0xFFFFFFFC`) reads in bounds, and is read as UnityPyBoost reads it.
24//!
25//! **The swap and the unpack.** UnityPyBoost swaps each component of 2 or
26//! 4 bytes when asked (`Mesh.cpp:77-96`, which the handler asks for
27//! little-endian data, `helpers/MeshHelper.py:363`), and the handler reads
28//! the result big-endian (`>`), so a swapped component is read
29//! little-endian and an unswapped one big-endian. `struct`'s codes give
30//! Python `int`s and `float`s, whose values here are written from the IEEE
31//! 754 formats, matching `CPython` 3.11's results (the oracle's): `f`, a
32//! binary32 widened to binary64 as x86's `cvtss2sd` widens it (a NaN keeps
33//! its payload with its quiet bit set, which the oracle shows; [`widen`]),
34//! and `e`, a binary16 widened exactly, its NaN the platform's `NAN` with
35//! the half's sign and no payload ([`half`]). An oracle moved past Python
36//! 3.11 needs these checked again: 3.14 changes how `PyFloat_Unpack4`
37//! treats a NaN (gh-130317), which may change the bits [`widen`] matches
38//! (`PARITY.md` section 19.3's row on the mesh handler's later phases' parts). A format of
39//! no bytes (a dimension whose low four bits are 0) is `struct.error`
40//! "cannot iteratively unpack with a struct of length 0".
41//!
42//! **Normalised** (`PARITY.md` section 19.1, Tier C): where the handler
43//! asks, a channel in a `UNorm`, `SNorm` or byte colour format is read as
44//! `float`s by its [`Norm`] rule, where `struct.iter_unpack` gives UnityPy
45//! the integers (`crate::format`'s module docs).
46//!
47//! **Bounds.** The output's `f64` or `i64` values (or bytes) are charged to
48//! the caller's meter, and then counted as decode work on it, before
49//! anything is read (`docs/plans/extract.md` E59), so a refused charge
50//! counts no work.
51
52use std::sync::Arc;
53
54use unityrs_core::limits::{Charge, Meter, MeteredVec};
55
56use crate::error::{MeshError, StructError};
57use crate::format::{Norm, StructCode};
58
59/// One attribute: `len()` tuples of `dimension()` components, as
60/// `struct.iter_unpack` (or the copy of a `Mesh`'s skin) gives them, the
61/// values flat in tuple order. A compressed mesh's arrays are
62/// `PackedBitVector.reshape`'s lists, whose last tuple may be cut short:
63/// it is a tuple here too, of the components it holds.
64#[derive(Debug)]
65pub struct VertexArray {
66    dimension: usize,
67    values: Values,
68    lists: bool,
69    // Declared last: the charge is returned after the values are freed.
70    _charge: Charge,
71}
72
73const _: () = crate::send_sync::<VertexArray>();
74
75/// An attribute's values: Python `float`s, as `f64`, or `int`s, flat in
76/// tuple order.
77///
78/// Not `Clone`: the values are charged to the meter that `process` was
79/// given, for as long as the [`VertexArray`] holding them lives, and a copy
80/// would hold memory no charge covers.
81#[derive(Debug, PartialEq)]
82#[non_exhaustive]
83pub enum Values {
84    /// `float`s (struct codes `f` and `e`; a skin's weights).
85    Float(Vec<f64>),
86    /// `int`s (the integer codes; a skin's bone indices).
87    Int(Vec<i64>),
88    /// Each value a `float` or an `int`, as Python holds it: a compressed
89    /// mesh's normals, tangents and bone weights, whose `zeros` are `int`s
90    /// beside the `float`s unpacked ([`crate::compressed`]).
91    Mixed(Vec<Component>),
92}
93
94const _: () = crate::send_sync::<Values>();
95
96impl VertexArray {
97    /// Takes ownership of already charged components supplied by an API adapter.
98    #[must_use]
99    pub fn from_components(dimension: usize, values: MeteredVec<Component>) -> Self {
100        let (values, charge) = values.into_parts();
101        Self::new(dimension, Values::Mixed(values), charge)
102    }
103
104    /// An array of `values`, `dimension` to a tuple, holding the charge
105    /// for their memory.
106    pub(crate) fn new(dimension: usize, values: Values, charge: Charge) -> Self {
107        Self {
108            dimension,
109            values,
110            lists: false,
111            _charge: charge,
112        }
113    }
114
115    /// The array as UnityPy holds its rows as `list`s, not tuples.
116    pub(crate) fn into_lists(mut self) -> Self {
117        self.lists = true;
118        self
119    }
120
121    /// Whether UnityPy holds each row as a `list` (`PackedBitVector.reshape`'s
122    /// slices: a compressed mesh's vertices, UVs, float colours and bind
123    /// poses) rather than a `tuple` (`struct.iter_unpack`'s rows, a skin's,
124    /// and the compressed normals, tangents, skin and packed colours, which
125    /// `lists_to_tuples` or a comprehension makes tuples).
126    #[must_use]
127    pub fn rows_are_lists(&self) -> bool {
128        self.lists
129    }
130
131    /// The components of each tuple.
132    #[must_use]
133    pub fn dimension(&self) -> usize {
134        self.dimension
135    }
136
137    /// The number of values, flat.
138    fn values_len(&self) -> usize {
139        match &self.values {
140            Values::Float(v) => v.len(),
141            Values::Int(v) => v.len(),
142            Values::Mixed(v) => v.len(),
143        }
144    }
145
146    /// The number of tuples, a last one cut short counted: Python's
147    /// `len()` of the list UnityPy holds. No values at dimension 0 is no
148    /// tuple.
149    #[must_use]
150    pub fn len(&self) -> usize {
151        if self.dimension == 0 {
152            return 0;
153        }
154        self.values_len().div_ceil(self.dimension)
155    }
156
157    /// The components tuple `tuple` holds: [`Self::dimension`], or fewer
158    /// for a last tuple cut short; `None` past the tuples.
159    #[must_use]
160    pub fn tuple_len(&self, tuple: usize) -> Option<usize> {
161        if tuple >= self.len() {
162            return None;
163        }
164        let from = tuple.checked_mul(self.dimension)?;
165        Some((self.values_len() - from).min(self.dimension))
166    }
167
168    /// Whether it holds no tuple.
169    #[must_use]
170    pub fn is_empty(&self) -> bool {
171        self.len() == 0
172    }
173
174    /// The values, flat.
175    #[must_use]
176    pub fn values(&self) -> &Values {
177        &self.values
178    }
179
180    /// Component `component` of tuple `tuple`, as a Python `float` or
181    /// `int`, whichever form holds it; `None` past the tuples
182    /// ([`Self::len`]) or past the tuple's components
183    /// ([`Self::tuple_len`]: a last tuple cut short holds fewer), where
184    /// Python's index raises `IndexError`.
185    #[must_use]
186    pub fn component(&self, tuple: usize, component: usize) -> Option<Component> {
187        if component >= self.tuple_len(tuple)? {
188            return None;
189        }
190        let at = tuple.checked_mul(self.dimension)?.checked_add(component)?;
191        match &self.values {
192            Values::Float(v) => v.get(at).copied().map(Component::Float),
193            Values::Int(v) => v.get(at).copied().map(Component::Int),
194            Values::Mixed(v) => v.get(at).copied(),
195        }
196    }
197}
198
199/// One component of a [`VertexArray`]'s tuple ([`VertexArray::component`]).
200#[derive(Clone, Copy, Debug, PartialEq)]
201#[non_exhaustive]
202pub enum Component {
203    /// A Python `float`.
204    Float(f64),
205    /// A Python `int`.
206    Int(i64),
207}
208
209const _: () = crate::send_sync::<Component>();
210
211impl Component {
212    /// The value as a Python `float`: an `int` converted as `float(i)`
213    /// converts it, to the nearest `f64`, ties to even.
214    #[must_use]
215    #[allow(clippy::cast_precision_loss)] // Python's own rounding (doc above).
216    pub fn as_f64(self) -> f64 {
217        match self {
218            Self::Float(f) => f,
219            Self::Int(i) => i as f64,
220        }
221    }
222
223    /// Python's truth value: `0`, `0.0` and `-0.0` are false, every other
224    /// value (a NaN included) true.
225    #[must_use]
226    pub fn is_truthy(self) -> bool {
227        match self {
228            Self::Float(f) => f != 0.0,
229            Self::Int(i) => i != 0,
230        }
231    }
232}
233
234/// The arguments of `UnityPyBoost.unpack_vertexdata` after Python's
235/// conversion to C (`UnityPyBoost/Mesh.cpp:26-43`): each a `uint32_t`, the
236/// component size an `int` that the arithmetic converts to one.
237#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
238pub struct Gather {
239    /// `componentByteSize`: 1, 2 or 4 from a struct code.
240    pub component_byte_size: u32,
241    /// `m_VertexCount`.
242    pub vertex_count: u32,
243    /// `m_StreamOffset`.
244    pub stream_offset: u32,
245    /// `m_StreamStride`.
246    pub stream_stride: u32,
247    /// `m_ChannelOffset`.
248    pub channel_offset: u32,
249    /// `m_ChannelDimension`: the channel's dimension, its low four bits.
250    pub channel_dimension: u32,
251    /// `swap`: swap each component of 2 or 4 bytes.
252    pub swap: bool,
253}
254
255const _: () = crate::send_sync::<Gather>();
256
257impl Gather {
258    /// The output's length, and a check that every component read lies in
259    /// `len` bytes of data (module docs): the bounds check UnityPyBoost
260    /// makes, then the reads and the buffer it would make past it.
261    fn check(&self, len: usize) -> Result<u64, MeshError> {
262        let cbs = self.component_byte_size;
263        let dim = self.channel_dimension;
264        // UnityPy Mesh.cpp:50: every term a `uint32_t`, so it wraps.
265        let max_access = self
266            .vertex_count
267            .wrapping_sub(1)
268            .wrapping_mul(self.stream_stride)
269            .wrapping_add(self.channel_offset)
270            .wrapping_add(self.stream_offset)
271            .wrapping_add(cbs.wrapping_mul(dim.wrapping_sub(1)))
272            .wrapping_add(cbs);
273        if u64::from(max_access) > u64::try_from(len).unwrap_or(u64::MAX) {
274            return Err(MeshError::OutOfBounds);
275        }
276        // UnityPy Mesh.cpp:47: the buffer is the wrapped product; past it
277        // the copy writes outside it.
278        let wrapped = self.vertex_count.wrapping_mul(dim).wrapping_mul(cbs);
279        let exact = u128::from(self.vertex_count) * u128::from(dim) * u128::from(cbs);
280        if exact != u128::from(wrapped) {
281            return Err(MeshError::WrappedAccess);
282        }
283        Ok(u64::from(wrapped))
284    }
285
286    /// The offset of vertex `v`'s component `d`, wrapped as
287    /// UnityPyBoost's `uint32_t`s wrap (`UnityPy Mesh.cpp:68`, `:71`).
288    fn offset(&self, v: u32, d: u32) -> u32 {
289        self.stream_offset
290            .wrapping_add(self.channel_offset)
291            .wrapping_add(self.stream_stride.wrapping_mul(v))
292            .wrapping_add(self.component_byte_size.wrapping_mul(d))
293    }
294
295    /// Visits each component's bytes in output order, after the checks;
296    /// a component outside the data is [`MeshError::WrappedAccess`].
297    fn each(
298        &self,
299        data: &[u8],
300        mut visit: impl FnMut(&[u8]) -> Result<(), MeshError>,
301    ) -> Result<(), MeshError> {
302        let cbs = usize::try_from(self.component_byte_size).unwrap_or(usize::MAX);
303        for v in 0..self.vertex_count {
304            for d in 0..self.channel_dimension {
305                let at = usize::try_from(self.offset(v, d)).unwrap_or(usize::MAX);
306                let src = at
307                    .checked_add(cbs)
308                    .and_then(|end| data.get(at..end))
309                    .ok_or(MeshError::WrappedAccess)?;
310                visit(src)?;
311            }
312        }
313        Ok(())
314    }
315}
316
317/// UnityPyBoost's output: the gathered components, each of 2 or 4 bytes
318/// swapped when asked.
319#[derive(Debug)]
320pub struct ComponentBytes {
321    bytes: Vec<u8>,
322    // Declared last: the charge is returned after the bytes are freed.
323    _charge: Charge,
324}
325
326const _: () = crate::send_sync::<ComponentBytes>();
327
328impl ComponentBytes {
329    /// The bytes.
330    #[must_use]
331    pub fn as_slice(&self) -> &[u8] {
332        &self.bytes
333    }
334}
335
336/// `UnityPyBoost.unpack_vertexdata(data, ...)` (`UnityPyBoost/Mesh.cpp:23-210`):
337/// the gather, its check and its swap (module docs), the output charged to
338/// `meter` before it is allocated and counted as decode work.
339pub fn unpack_vertexdata(
340    data: &[u8],
341    args: &Gather,
342    meter: &Arc<Meter>,
343) -> Result<ComponentBytes, MeshError> {
344    let length = args.check(data.len())?;
345    let n = usize::try_from(length).map_err(|_| MeshError::WrappedAccess)?;
346    // Charged, then counted: a refused charge counts no work.
347    let mut out = MeteredVec::<u8>::with_capacity(meter, n)?;
348    meter.count_decode(length)?;
349    let swap = args.swap && matches!(args.component_byte_size, 2 | 4);
350    // UnityPy Mesh.cpp:66-75 copies each component. A component of no bytes
351    // (a size no struct code has, so only a direct caller's) copies nothing
352    // wherever it points: with no output there is nothing to read, and the
353    // loop, up to 2^32 x 15 steps of no work, does not run.
354    if length == 0 {
355        let (bytes, charge) = out.into_parts();
356        return Ok(ComponentBytes {
357            bytes,
358            _charge: charge,
359        });
360    }
361    args.each(data, |src| {
362        // UnityPy Mesh.cpp:77-96: each component of 2 or 4 bytes reversed.
363        if swap {
364            for &b in src.iter().rev() {
365                out.push(b)?;
366            }
367        } else {
368            out.extend_from_slice(src)?;
369        }
370        Ok(())
371    })?;
372    let (bytes, charge) = out.into_parts();
373    Ok(ComponentBytes {
374        bytes,
375        _charge: charge,
376    })
377}
378
379/// The gather and `struct.iter_unpack(f">{dimension}{code}", ...)` in one
380/// pass (`helpers/MeshHelper.py:366-392`), with no buffer between: the
381/// values of one channel, charged to `meter` before they are allocated.
382/// With `norm`, each integer is normalised to a `float` by its rule
383/// (`crate::format`'s module docs, Tier C), where UnityPy keeps the
384/// integer.
385pub(crate) fn unpack_channel(
386    data: &[u8],
387    args: &Gather,
388    code: StructCode,
389    norm: Option<Norm>,
390    meter: &Arc<Meter>,
391) -> Result<VertexArray, MeshError> {
392    let length = args.check(data.len())?;
393    let dimension = usize::try_from(args.channel_dimension).unwrap_or(usize::MAX);
394    // UnityPy MeshHelper.py:392: a format of no bytes refuses to iterate,
395    // whatever the buffer (UnityPyBoost has returned `b""`).
396    if dimension == 0 {
397        return Err(MeshError::Struct(StructError::ZeroLength));
398    }
399    let n = usize::try_from(u64::from(args.vertex_count) * u64::from(args.channel_dimension))
400        .map_err(|_| MeshError::WrappedAccess)?;
401    // The swapped bytes read big-endian are the source read little-endian
402    // (module docs); a component of one byte is never swapped. Each output
403    // is charged, then counted: a refused charge counts no work.
404    let little = args.swap;
405    if code.is_float() || norm.is_some() {
406        let mut out = MeteredVec::<f64>::with_capacity(meter, n)?;
407        meter.count_decode(length)?;
408        args.each(data, |src| {
409            out.push(match norm {
410                // PARITY.md section 19.1: UnityPy keeps the integer.
411                Some(rule) if !code.is_float() => rule.value(code, int(code, src, little)),
412                _ => float(code, src, little),
413            })?;
414            Ok(())
415        })?;
416        let (v, charge) = out.into_parts();
417        Ok(VertexArray::new(dimension, Values::Float(v), charge))
418    } else {
419        let mut out = MeteredVec::<i64>::with_capacity(meter, n)?;
420        meter.count_decode(length)?;
421        args.each(data, |src| {
422            out.push(int(code, src, little))?;
423            Ok(())
424        })?;
425        let (v, charge) = out.into_parts();
426        Ok(VertexArray::new(dimension, Values::Int(v), charge))
427    }
428}
429
430/// A component's bytes in little-endian order: as they are when read
431/// little-endian, reversed when read big-endian.
432fn le(src: &[u8], little: bool) -> [u8; 4] {
433    let mut a = [0u8; 4];
434    if little {
435        a.iter_mut().zip(src).for_each(|(o, b)| *o = *b);
436    } else {
437        a.iter_mut()
438            .zip(src.iter().rev())
439            .for_each(|(o, b)| *o = *b);
440    }
441    a
442}
443
444/// An integer code's value (`B b H h I i`).
445fn int(code: StructCode, src: &[u8], little: bool) -> i64 {
446    let [a, b, c, d] = le(src, little);
447    match code {
448        StructCode::I8 => i64::from(i8::from_le_bytes([a])),
449        StructCode::U16 => i64::from(u16::from_le_bytes([a, b])),
450        StructCode::I16 => i64::from(i16::from_le_bytes([a, b])),
451        StructCode::U32 => i64::from(u32::from_le_bytes([a, b, c, d])),
452        StructCode::I32 => i64::from(i32::from_le_bytes([a, b, c, d])),
453        // `B`; the float codes never come here.
454        StructCode::U8 | StructCode::F16 | StructCode::F32 => i64::from(a),
455    }
456}
457
458/// A float code's value (`f`, `e`).
459fn float(code: StructCode, src: &[u8], little: bool) -> f64 {
460    let [a, b, c, d] = le(src, little);
461    match code {
462        StructCode::F16 => half(u16::from_le_bytes([a, b])),
463        _ => widen(u32::from_le_bytes([a, b, c, d])),
464    }
465}
466
467/// A C `float`'s bits widened to `double` as x86's `cvtss2sd` widens them:
468/// exactly, and a NaN with its payload kept and its quiet bit set (module
469/// docs). A typetree `float`'s value is widened the same way, by
470/// UnityPyBoost's `PyFloat_FromDouble` of it.
471pub(crate) fn widen(bits: u32) -> f64 {
472    let f = f32::from_bits(bits);
473    if f.is_nan() {
474        let sign = u64::from(bits >> 31) << 63;
475        let payload = u64::from((bits & 0x007f_ffff) | 0x0040_0000);
476        f64::from_bits(sign | 0x7ff0_0000_0000_0000 | (payload << 29))
477    } else {
478        f64::from(f)
479    }
480}
481
482/// An IEEE 754 binary16's bits as the binary64 of the same value: the
483/// sign kept, a normal half's exponent rebiased from 15 to 1023 with its
484/// ten fraction bits at the top of the 52, a subnormal (and zero) its
485/// fraction times 2^-24, which binary64 holds exactly, and the infinities
486/// kept. A NaN is the quiet NaN `0x7ff8000000000000` with the half's sign
487/// and no payload, matching `CPython` 3.11's `struct` `e`, which returns the
488/// platform's `NAN` for one.
489pub(crate) fn half(bits: u16) -> f64 {
490    let sign = u64::from(bits >> 15) << 63;
491    let exponent = u64::from((bits >> 10) & 0x1f);
492    let fraction = bits & 0x03ff;
493    let magnitude = match exponent {
494        0 => (f64::from(fraction) * 2f64.powi(-24)).to_bits(),
495        0x1f if fraction == 0 => f64::INFINITY.to_bits(),
496        0x1f => 0x7ff8_0000_0000_0000,
497        _ => ((exponent + 1023 - 15) << 52) | (u64::from(fraction) << 42),
498    };
499    f64::from_bits(sign | magnitude)
500}
501
502#[cfg(test)]
503mod tests {
504    use std::sync::Arc;
505
506    use unityrs_core::limits::{Charge, Meter};
507
508    use super::{Component, Gather, Values, VertexArray, half, unpack_vertexdata, widen};
509    use crate::error::MeshError;
510
511    fn args(vc: u32, soff: u32, stride: u32, choff: u32, dim: u32, cbs: u32) -> Gather {
512        Gather {
513            component_byte_size: cbs,
514            vertex_count: vc,
515            stream_offset: soff,
516            stream_stride: stride,
517            channel_offset: choff,
518            channel_dimension: dim,
519            swap: true,
520        }
521    }
522
523    #[test]
524    fn halves_and_floats_widen_as_the_oracle_does() {
525        // The oracle's bits (Python 3.11 on x86-64).
526        assert_eq!(half(0x7c00), f64::INFINITY);
527        assert_eq!(half(0x7c01).to_bits(), 0x7ff8_0000_0000_0000);
528        assert_eq!(half(0x7e00).to_bits(), 0x7ff8_0000_0000_0000);
529        assert_eq!(half(0xfc01).to_bits(), 0xfff8_0000_0000_0000);
530        assert_eq!(half(0x3c00), 1.0);
531        assert_eq!(half(0x0001), 2f64.powi(-24));
532        assert_eq!(half(0x8000).to_bits(), (-0.0f64).to_bits());
533        assert_eq!(widen(0x7f80_0001).to_bits(), 0x7ff8_0000_2000_0000);
534        assert_eq!(widen(0xffa0_0005).to_bits(), 0xfffc_0000_a000_0000);
535        assert_eq!(widen(0x7fc0_0000).to_bits(), 0x7ff8_0000_0000_0000);
536    }
537
538    #[test]
539    fn every_half_widens_to_its_value() {
540        // Against the half's value computed apart, (1 + f/1024) x 2^(e-15),
541        // for every finite half.
542        for bits in 0..=u16::MAX {
543            let (e, f) = (i32::from((bits >> 10) & 0x1f), f64::from(bits & 0x3ff));
544            if e == 0x1f {
545                continue;
546            }
547            let x = if e == 0 {
548                f / 1024.0 * 2f64.powi(-14)
549            } else {
550                (1.0 + f / 1024.0) * 2f64.powi(e - 15)
551            };
552            let want = if bits & 0x8000 != 0 { -x } else { x };
553            assert_eq!(half(bits).to_bits(), want.to_bits(), "{bits:#06x}");
554        }
555    }
556
557    #[test]
558    fn a_backward_stride_reads_as_unitypyboost_reads_it() {
559        // Stride -4: vertices at 8, 4, 0. The check's sum wraps to 12.
560        let data: Vec<u8> = (0..12).collect();
561        let a = args(3, 8, 0xFFFF_FFFC, 0, 1, 4);
562        let out = unpack_vertexdata(&data, &a, &Meter::unlimited()).unwrap();
563        assert_eq!(out.as_slice(), &[11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]);
564    }
565
566    #[test]
567    fn a_wrapped_offset_past_the_data_is_refused() {
568        // The offset 0xFFFFFFF0 passes the wrapped check of 16 bytes, and
569        // UnityPyBoost would read 4 GiB past its buffer.
570        let data = [0u8; 16];
571        let a = args(8, 0xFFFF_FFF0, 4, 0, 1, 4);
572        let e = unpack_vertexdata(&data, &a, &Meter::unlimited()).unwrap_err();
573        assert!(matches!(e, MeshError::WrappedAccess), "{e:?}");
574        let a = args(8, 0, 4, 0, 1, 4);
575        let e = unpack_vertexdata(&data, &a, &Arc::clone(&Meter::unlimited())).unwrap_err();
576        assert!(matches!(e, MeshError::OutOfBounds), "{e:?}");
577    }
578
579    fn array(dimension: usize, values: Values) -> VertexArray {
580        VertexArray::new(dimension, values, Charge::zero(&Meter::unlimited()))
581    }
582
583    #[test]
584    fn a_component_is_a_python_float_or_int_by_the_form_that_holds_it() {
585        let floats = array(2, Values::Float(vec![0.5, -1.0, 2.0, 3.5]));
586        assert_eq!(floats.len(), 2);
587        assert_eq!(floats.component(0, 1), Some(Component::Float(-1.0)));
588        assert_eq!(floats.component(1, 0), Some(Component::Float(2.0)));
589        let ints = array(3, Values::Int(vec![1, -2, 3, i64::MAX, 0, -7]));
590        assert_eq!(ints.component(1, 0), Some(Component::Int(i64::MAX)));
591        assert_eq!(ints.component(0, 2), Some(Component::Int(3)));
592        // `float(i)`: the nearest f64, ties to even.
593        assert_eq!(
594            Component::Int(i64::MAX).as_f64(),
595            9_223_372_036_854_775_808.0
596        );
597        assert_eq!(
598            Component::Int((1 << 53) + 1).as_f64(),
599            9_007_199_254_740_992.0
600        );
601        assert_eq!(Component::Float(-0.25).as_f64(), -0.25);
602    }
603
604    #[test]
605    fn a_component_past_the_tuples_or_its_tuple_is_none() {
606        let a = array(2, Values::Float(vec![1.0, 2.0, 3.0]));
607        // Three values of dimension 2: a whole tuple and one cut short, as
608        // `reshape` gives them.
609        assert_eq!(a.len(), 2);
610        assert_eq!(
611            (a.tuple_len(0), a.tuple_len(1), a.tuple_len(2)),
612            (Some(2), Some(1), None)
613        );
614        assert_eq!(a.component(0, 2), None);
615        assert_eq!(a.component(0, 1), Some(Component::Float(2.0)));
616        assert_eq!(a.component(1, 0), Some(Component::Float(3.0)));
617        assert_eq!(a.component(1, 1), None);
618        assert_eq!(a.component(2, 0), None);
619        assert_eq!(a.component(usize::MAX, 1), None);
620        assert_eq!(a.component(usize::MAX / 2 + 1, 0), None);
621        let empty = array(0, Values::Int(vec![1, 2]));
622        assert_eq!((empty.len(), empty.component(0, 0)), (0, None));
623    }
624
625    #[test]
626    fn truth_is_python_s() {
627        assert!(!Component::Float(0.0).is_truthy());
628        assert!(!Component::Float(-0.0).is_truthy());
629        assert!(Component::Float(f64::NAN).is_truthy());
630        assert!(Component::Float(f64::MIN_POSITIVE / 2.0).is_truthy());
631        assert!(!Component::Int(0).is_truthy());
632        assert!(Component::Int(-1).is_truthy());
633    }
634}