Skip to main content

unityrs_testkit/
depth.rs

1//! Deep values (plan section 3.10, "Bounds"): the shapes of
2//! `tools/fixtures/walk.py`'s `depth.json`, built the same way.
3//!
4//! Ref type `A` nests its levels (one kind, or every kind after every
5//! other) as deep as one tree may go around a
6//! `ReferencedObject` whose data is the next `A`; the chain ends at ref type
7//! `Z` (`Z { int z }`). Every ref type's namespace is `n` and its assembly
8//! `a`. Rows and bytes are built without recursion.
9
10use crate::writer::ByteWriter;
11
12/// One level of a shape's nesting, outermost first (`walk.py`'s
13/// `DEPTH_SHAPES`).
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum Wrap {
16    /// A class holding the next level.
17    Class,
18    /// A vector (unflagged element) of the next level.
19    Vector,
20    /// A vector whose element, the next level, carries the align flag: the
21    /// pure-Python reader's `read_value_array`.
22    Aligned,
23    /// An aligned vector of a class holding the next level.
24    ClassArray,
25    /// A pair whose `first` is the next level.
26    Pair,
27    /// An aligned vector of pairs whose `first` is a class holding the next
28    /// level (`read_value_array`'s `lambda`).
29    PairArray,
30}
31
32impl Wrap {
33    /// The wrap `walk.py` names `name`.
34    #[must_use]
35    pub fn of(name: &str) -> Option<Self> {
36        Some(match name {
37            "Class" => Self::Class,
38            "Vector" => Self::Vector,
39            "Aligned" => Self::Aligned,
40            "ClassArray" => Self::ClassArray,
41            "Pair" => Self::Pair,
42            "PairArray" => Self::PairArray,
43            _ => return None,
44        })
45    }
46
47    fn vector(self) -> bool {
48        matches!(
49            self,
50            Self::Vector | Self::Aligned | Self::ClassArray | Self::PairArray
51        )
52    }
53}
54
55/// A typetree row: level, type, name, meta flag.
56pub type Row = (u8, &'static str, &'static str, i32);
57
58/// The align flag.
59pub const ALIGN: i32 = 0x4000;
60
61/// Ref type `Z`'s rows, which ends a chain.
62pub const Z_ROWS: [Row; 2] = [(0, "Z", "Base", 0), (1, "int", "z", 0)];
63
64/// One shape: ref type `A`'s rows (also the object's tree) and the bytes of
65/// one `A` around its `ReferencedObject`.
66#[derive(Clone, Debug)]
67pub struct Depth {
68    /// Ref type `A`'s rows.
69    pub rows: Vec<Row>,
70    prefix: Vec<u8>,
71    suffix: Vec<u8>,
72}
73
74impl Depth {
75    /// `walk.py`'s `depth_rows`.
76    ///
77    /// # Panics
78    ///
79    /// Past 255 levels.
80    #[must_use]
81    pub fn new(wraps: &[Wrap]) -> Self {
82        let mut rows = vec![(0, "A", "Base", 0)];
83        let (mut level, mut name, mut meta) = (1u8, "x", 0);
84        let mut tails = Vec::new();
85        let at = |level: u8, by: u8| level.checked_add(by).expect("at most 255 levels");
86        for &w in wraps {
87            if w.vector() {
88                rows.extend([
89                    (level, "vector", name, meta),
90                    (at(level, 1), "Array", "Array", 0),
91                    (at(level, 2), "int", "size", 0),
92                ]);
93                (level, name, meta) = (
94                    at(level, 2),
95                    "data",
96                    if w == Wrap::Vector { 0 } else { ALIGN },
97                );
98            }
99            match w {
100                Wrap::Class | Wrap::ClassArray => {
101                    rows.push((level, "C", name, meta));
102                    (level, name, meta) = (at(level, 1), "c", 0);
103                }
104                Wrap::Pair => {
105                    rows.push((level, "pair", name, meta));
106                    tails.push((at(level, 1), "int", "second", 0));
107                    (level, name, meta) = (at(level, 1), "first", 0);
108                }
109                Wrap::PairArray => {
110                    rows.extend([(level, "pair", name, meta), (at(level, 1), "C", "first", 0)]);
111                    tails.push((at(level, 1), "int", "second", 0));
112                    (level, name, meta) = (at(level, 2), "c", 0);
113                }
114                Wrap::Vector | Wrap::Aligned => {}
115            }
116        }
117        rows.extend([
118            (level, "ReferencedObject", name, meta),
119            (at(level, 1), "ReferencedManagedType", "type", 0),
120            (at(level, 2), "string", "class", 0),
121            (at(level, 2), "string", "ns", 0),
122            (at(level, 2), "string", "asm", 0),
123            (at(level, 1), "ReferencedObjectData", "data", 0),
124        ]);
125        rows.extend(tails.into_iter().rev());
126        let mut prefix = ByteWriter::le();
127        for w in wraps {
128            if !matches!(w, Wrap::Class | Wrap::Pair) {
129                prefix.i32(1);
130            }
131        }
132        let mut suffix = ByteWriter::le();
133        for w in wraps.iter().rev() {
134            if matches!(w, Wrap::Pair | Wrap::PairArray) {
135                suffix.i32(5);
136            }
137        }
138        Self {
139            rows,
140            prefix: prefix.into_inner(),
141            suffix: suffix.into_inner(),
142        }
143    }
144
145    /// `n` `A`s, the last holding a `Z` (`walk.py`'s `depth_data`).
146    #[must_use]
147    pub fn data(&self, n: usize) -> Vec<u8> {
148        let mut w = ByteWriter::le();
149        for i in 1..=n {
150            w.bytes(&self.prefix);
151            for s in [if i == n { "Z" } else { "A" }, "n", "a"] {
152                w.i32(i32::try_from(s.len()).unwrap_or(0))
153                    .bytes(s.as_bytes())
154                    .align(4);
155            }
156        }
157        w.i32(7);
158        let mut d = w.into_inner();
159        d.extend(self.suffix.repeat(n));
160        d
161    }
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    #[test]
169    fn a_pair_array_level_nests_four_deep() {
170        let d = Depth::new(&[Wrap::PairArray]);
171        let types: Vec<&str> = d.rows.iter().map(|r| r.1).collect();
172        assert_eq!(
173            types,
174            [
175                "A",
176                "vector",
177                "Array",
178                "int",
179                "pair",
180                "C",
181                "ReferencedObject",
182                "ReferencedManagedType",
183                "string",
184                "string",
185                "string",
186                "ReferencedObjectData",
187                "int"
188            ]
189        );
190        assert_eq!(d.rows.last(), Some(&(4, "int", "second", 0)));
191        assert_eq!(d.data(1).len(), 4 + 3 * 8 + 4 + 4);
192    }
193}