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