unityrs-export 1.0.0

Unity asset exports beside the textures: sprites, the NGUI atlas cutter and its crops, and the UnityPy extractor tree.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! The key rules' and the templates' unit tests (module docs): expansion
//! to the stop and the code point it cuts, `safe`, and each rule in its
//! order.

use super::{
    KeyRule, STOP, Template, TemplateError, TemplateKind, TemplateRefusal, Token, Var, check,
    check_member, check_member_template, check_prefixed, check_template, cut_tail, safe, safe_into,
    tokens,
};

fn expanded<'v>(t: &Template, value: impl Fn(Var) -> &'v [u8]) -> Vec<u8> {
    let mut out = Vec::with_capacity(STOP);
    let at = out.as_ptr();
    let _ = t.expand(value, &mut out);
    assert_eq!(out.as_ptr(), at, "the expansion grew its buffer");
    out
}

#[test]
fn the_stop_tells_a_cut_code_point_from_an_invalid_byte() {
    // Review round 3's P3: 1,023 bytes, then a four-byte character the
    // stop cuts after two of its bytes: two bytes of a cut code point.
    let t = Template::parse("{atlas}", TemplateKind::AtlasJson).unwrap();
    let mut v = vec![b'a'; 1023];
    v.extend("\u{1f600}".as_bytes());
    let mut out = Vec::with_capacity(STOP);
    assert_eq!(t.expand(|_| &v, &mut out), 2);
    // The same two bytes invalid in the value: one code point each.
    v.truncate(1025);
    v.push(b'z');
    assert_eq!(t.expand(|_| &v, &mut out), 0);
    // A literal cut the same way, and a stop on a boundary.
    let lit = format!("{}\u{e9}x", "b".repeat(1024));
    let t = Template::parse(&lit, TemplateKind::AtlasJson).unwrap();
    assert_eq!(t.expand(|_| b"", &mut out), 1);
    assert_eq!(cut_tail(b"abc", 2), 0);
    assert_eq!(cut_tail("a\u{e9}".as_bytes(), 3), 0);
    assert_eq!(cut_tail(b"a\xff\xff", 2), 0);
    // Review round 4's A3, Codex's case: the code point spans two
    // variables, its lead the last byte of `{atlas}` (1,024 bytes), the
    // stop one byte into `{sprite}`: two bytes cut.
    let t = Template::parse("{atlas}{sprite}", TemplateKind::AtlasSprite).unwrap();
    let mut atlas = [b"a/".repeat(511), b"x".to_vec()].concat();
    atlas.push(0xF0);
    let sprite = b"\x9f\x98\x80z";
    let value = |v: Var| match v {
        Var::Atlas => atlas.as_slice(),
        _ => sprite.as_slice(),
    };
    assert_eq!(t.expand(value, &mut out), 2);
    // The stop on the boundary of the two, the code point past it: its
    // lead and second byte before the stop, read on into `{sprite}`.
    atlas.push(0x9F);
    let value = |v: Var| match v {
        Var::Atlas => atlas.as_slice(),
        _ => &sprite[1..],
    };
    assert_eq!(t.expand(value, &mut out), 2);
    // A `safe_` piece after a lead: ASCII, so the lead is invalid.
    let t = Template::parse("{atlas}{safe_sprite}", TemplateKind::AtlasSprite).unwrap();
    let value = |v: Var| match v {
        Var::Atlas => atlas.as_slice(),
        _ => sprite.as_slice(),
    };
    assert_eq!(t.expand(value, &mut out), 0);
}

#[test]
fn an_expansion_stops_one_byte_past_the_bound() {
    let t = Template::parse("a/{atlas}/b", TemplateKind::AtlasJson).unwrap();
    let big = vec![b'x'; 5000];
    assert_eq!(expanded(&t, |_| &big).len(), STOP);
    assert_eq!(expanded(&t, |_| b"n"), b"a/n/b");
    // A `safe_` variable of a huge value is made only as far as the
    // room: the same bytes as the whole value's `safe()`.
    let t = Template::parse("{safe_atlas}", TemplateKind::AtlasJson).unwrap();
    let huge = [b"..".as_slice(), &vec![b'a'; 1 << 24], b"..."].concat();
    assert_eq!(expanded(&t, |_| &huge), vec![b'a'; STOP]);
}

#[test]
fn safe_into_is_safes_prefix() {
    let cases: [&[u8]; 9] = [
        b"..x..",
        b"a..b...",
        b"...",
        b"",
        b"a b/c",
        "\u{e4}tlas".as_bytes(),
        b"bad\xff\xfe..",
        b"\xe2\x82.",
        b".a.",
    ];
    for bytes in cases {
        let whole = safe(bytes);
        for room in 0..=whole.len() + 1 {
            let mut out = b"pre".to_vec();
            safe_into(bytes, room, &mut out);
            let want = &whole.as_bytes()[..room.min(whole.len())];
            assert_eq!(&out[3..], want, "{bytes:?} at {room}");
        }
    }
}

#[test]
fn a_key_past_the_bound_is_decided_on_its_first_1025_bytes() {
    let at = |n: usize, tail: &[u8]| {
        let mut k = vec![b'a'; n];
        for (i, b) in k.iter_mut().enumerate() {
            if i % 200 == 199 {
                *b = b'/';
            }
        }
        k.extend_from_slice(tail);
        check(&k).unwrap_err()
    };
    // A control character within the first 1,025 bytes is reported;
    // one past them is not seen, and the key is too long.
    assert_eq!(
        at(1001, b"\tzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"),
        KeyRule::ControlChar
    );
    assert_eq!(at(1025, b"\t"), KeyRule::TooLong);
    // The end is past what is read: no trailing slash, no last dot
    // segment, no cut code point.
    assert_eq!(at(1024, b"/"), KeyRule::TooLong);
    assert_eq!(at(1023, b"/."), KeyRule::TooLong);
    assert_eq!(at(1024, "\u{e9}".as_bytes()), KeyRule::TooLong);
    // A dot segment the bytes settle is reported.
    assert_eq!(
        at(1001, b"/../aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"),
        KeyRule::DotSegment
    );
    let mut seg = vec![b'a'; 300];
    seg.extend(vec![b'b'; 900]);
    assert_eq!(check(&seg).unwrap_err(), KeyRule::SegmentTooLong);
}

#[test]
fn a_cut_code_point_still_counts_in_its_segments_length() {
    // Review round 2's C4: 769 bytes of short segments, then 254 bytes
    // and a four-byte character. The stop at 1,025 cuts the character
    // after two of its bytes, so the last segment read is 256 bytes:
    // `segment_too_long`, before `too_long`.
    let key = |head: &[u8], x: usize| {
        let mut k = head.to_vec();
        k.extend(b"a/".repeat(383));
        k.extend(vec![b'x'; x]);
        k.extend("\u{1f600}".as_bytes());
        k
    };
    let long = key(b"aa/", 254);
    assert_eq!(long.len(), 1027);
    assert_eq!(check(&long), Err(KeyRule::SegmentTooLong));
    assert_eq!(check_member(&long), Err(KeyRule::SegmentTooLong));
    // One byte fewer in the segment: 255 bytes read, and too long.
    let short = key(b"aaa/", 253);
    assert_eq!(check(&short), Err(KeyRule::TooLong));
    assert_eq!(check_member(&short), Err(KeyRule::TooLong));
}

#[test]
fn a_key_is_checked_then_checked_again_after_the_prefix() {
    let mut scratch = Vec::with_capacity(STOP);
    let at = scratch.as_ptr();
    assert_eq!(
        check_prefixed(b"a.png", "out/", &mut scratch).unwrap(),
        "a.png"
    );
    assert_eq!(
        check_prefixed(b"a.png", "_unityrs/", &mut scratch).unwrap_err(),
        KeyRule::ReservedPrefix
    );
    let long = format!("{}c", "ab/".repeat(333));
    assert_eq!(
        check_prefixed(long.as_bytes(), &"p/".repeat(20), &mut scratch).unwrap_err(),
        KeyRule::TooLong
    );
    assert_eq!(scratch.as_ptr(), at, "the check grew its buffer");
    // The key's own refusal comes first.
    assert_eq!(
        check_prefixed(b"a//b", "_unityrs/", &mut scratch).unwrap_err(),
        KeyRule::EmptySegment
    );
}

#[test]
fn a_member_path_takes_every_rule_but_the_reserved_ones() {
    assert_eq!(check_member(b"_unityrs/a").unwrap(), "_unityrs/a");
    assert_eq!(
        check_member(b"a/.unityrs-tmp-1").unwrap(),
        "a/.unityrs-tmp-1"
    );
    assert_eq!(check_member(b"a/").unwrap_err(), KeyRule::TrailingSlash);
}

#[test]
fn safe_replaces_per_code_point_and_strips_dots() {
    assert_eq!(safe("\u{e4}tlas".as_bytes()), "_tlas");
    assert_eq!(safe(b"a b/c"), "a_b_c");
    assert_eq!(safe(b"..x.."), "x");
    assert_eq!(safe(b"..."), "unnamed");
    assert_eq!(safe(b""), "unnamed");
    assert_eq!(safe(b"bad\xff\xfe"), "bad__");
    assert_eq!(safe(b"\xe2\x82"), "__");
    assert_eq!(safe("\u{7cbe}\u{7075}".as_bytes()), "__");
    assert_eq!(safe(b"a..b."), "a..b");
}

#[test]
fn templates_parse_braces_and_refuse_unknown_variables() {
    let t = Template::parse("{{x}}/{atlas}-{sprite}.png", TemplateKind::AtlasSprite).unwrap();
    let key = expanded(&t, |v| match v {
        Var::Atlas => b"a",
        Var::Sprite => b"s",
        _ => b"",
    });
    assert_eq!(key, b"{x}/a-s.png");
    assert_eq!(
        Template::parse("{nope}", TemplateKind::AtlasJson),
        Err(TemplateError::Unknown("nope".to_owned()))
    );
    assert_eq!(
        Template::parse("{sprite}.json", TemplateKind::AtlasJson),
        Err(TemplateError::NotAllowed("sprite".to_owned()))
    );
    assert_eq!(
        Template::parse("{name}", TemplateKind::AtlasSprite),
        Err(TemplateError::NotAllowed("name".to_owned()))
    );
    assert_eq!(
        Template::parse("a}", TemplateKind::Texture),
        Err(TemplateError::Brace(1))
    );
    assert_eq!(
        Template::parse("a{b", TemplateKind::Texture),
        Err(TemplateError::Brace(1))
    );
    assert_eq!(
        Template::parse("", TemplateKind::Texture),
        Err(TemplateError::Empty)
    );
    assert!(Template::parse("{type}/{safe_name}_{path_id}", TemplateKind::Texture).is_ok());
    // `outputs.sprites` takes a texture's variables, no atlas's (2.1).
    let sprite = "{safe_input}/{type}/{name}-{safe_name}_{path_id}.png";
    assert!(Template::parse(sprite, TemplateKind::Sprite).is_ok());
    for name in ["atlas", "safe_atlas", "sprite", "safe_sprite"] {
        assert_eq!(
            Template::parse(&format!("{{{name}}}"), TemplateKind::Sprite),
            Err(TemplateError::NotAllowed(name.to_owned()))
        );
    }
    assert_eq!(
        Template::parse("{name}", TemplateKind::AtlasJson),
        Err(TemplateError::NotAllowed("name".to_owned()))
    );
    assert_eq!(TemplateKind::Sprite.name(), "sprite");
}

#[test]
fn the_first_rule_broken_names_the_refusal() {
    let bad = |k: &[u8]| check(k).unwrap_err();
    assert_eq!(bad(b""), KeyRule::Empty);
    assert_eq!(bad(b"a\xff/"), KeyRule::NotUtf8);
    assert_eq!(bad(b"/a\tb"), KeyRule::ControlChar);
    assert_eq!(bad(b"a\x7f"), KeyRule::ControlChar);
    assert_eq!(bad(b"/a//"), KeyRule::LeadingSlash);
    assert_eq!(bad(b"a//"), KeyRule::TrailingSlash);
    assert_eq!(bad(b"a//b"), KeyRule::EmptySegment);
    assert_eq!(bad(b"a/../b"), KeyRule::DotSegment);
    assert_eq!(bad(b"./b"), KeyRule::DotSegment);
    assert_eq!(bad(&[b'x'; 256]), KeyRule::SegmentTooLong);
    let long: Vec<u8> = [b"a/".as_slice(); 513].concat();
    assert_eq!(bad(&long[..1025]), KeyRule::TooLong);
    assert_eq!(bad(b"_unityrs"), KeyRule::ReservedPrefix);
    assert_eq!(bad(b"_unityrs/x"), KeyRule::ReservedPrefix);
    assert_eq!(bad(b"a/.unityrs-tmp-1"), KeyRule::ReservedName);
    assert_eq!(check(b"_unityrsx/a.png").unwrap(), "_unityrsx/a.png");
    assert_eq!(check(b"..a/b.").unwrap(), "..a/b.");
}

#[test]
fn the_sprites_kind_takes_the_object_variables() {
    for t in [
        "{type}/{name}.png",
        "{safe_name}_{path_id}",
        "{input}/{safe_input}",
    ] {
        assert!(Template::parse(t, TemplateKind::Sprite).is_ok(), "{t}");
    }
    for (t, name) in [("{atlas}", "atlas"), ("{safe_sprite}", "safe_sprite")] {
        assert_eq!(
            Template::parse(t, TemplateKind::Sprite),
            Err(TemplateError::NotAllowed(name.to_owned()))
        );
    }
}

/// The tokens are the grammar's pieces: a brace pair is one brace's
/// literal, borrowed from the text, and an error ends them.
#[test]
fn tokens_read_the_grammar_once() {
    let got: Vec<_> = tokens("a{{b}}/{name}c", TemplateKind::Texture).collect();
    assert_eq!(
        got,
        [
            Ok(Token::Lit("a")),
            Ok(Token::Lit("{")),
            Ok(Token::Lit("b")),
            Ok(Token::Lit("}")),
            Ok(Token::Lit("/")),
            Ok(Token::Var(Var::Name)),
            Ok(Token::Lit("c")),
        ]
    );
    let got: Vec<_> = tokens("a}b{name}", TemplateKind::Texture).collect();
    assert_eq!(got, [Ok(Token::Lit("a")), Err(TemplateError::Brace(1))]);
    assert_eq!(tokens("", TemplateKind::Texture).count(), 0);
}

fn literal_rule(text: &str) -> Option<KeyRule> {
    match check_template(text, TemplateKind::Texture) {
        Ok(()) => None,
        Err(TemplateRefusal::Literal(r)) => Some(r),
        Err(e) => panic!("{text}: {e}"),
    }
}

/// 2.1's literal checks, one case per rule, and what they leave to each
/// expansion.
#[test]
fn a_literal_part_that_breaks_a_key_rule_is_refused() {
    let long = "x".repeat(256);
    let cases: &[(&str, Option<KeyRule>)] = &[
        ("{input}/{name}.png", None),
        ("/{name}", Some(KeyRule::LeadingSlash)),
        ("{name}/", Some(KeyRule::TrailingSlash)),
        ("a/{name}/", Some(KeyRule::TrailingSlash)),
        ("a//{name}", Some(KeyRule::EmptySegment)),
        ("{input}//{name}", Some(KeyRule::EmptySegment)),
        ("a/./{name}", Some(KeyRule::DotSegment)),
        ("{name}/..", Some(KeyRule::DotSegment)),
        ("{name}/.../x", None),
        ("{name}/.x", None),
        ("_unityrs", Some(KeyRule::ReservedPrefix)),
        ("_unityrs/{name}", Some(KeyRule::ReservedPrefix)),
        ("_unityrs{name}", None),
        ("{name}_unityrs/x", None),
        ("{input}/.unityrs-tmp-a", Some(KeyRule::ReservedName)),
        ("{input}/.unityrs-tmp-{name}", None),
        ("{input}/.unityrs-tm", None),
        // A segment with a variable in it is each expansion's.
        ("{input}/.{name}", None),
        ("{input}/{{}}", None),
        // A control character is each expansion's too (2.1's list).
        ("{input}/a\u{1}", None),
        // The first rule in 2.3's order names the refusal.
        ("/a//./_x/", Some(KeyRule::LeadingSlash)),
        ("a//./", Some(KeyRule::TrailingSlash)),
    ];
    for (text, want) in cases {
        assert_eq!(literal_rule(text), *want, "{text}");
    }
    let t = format!("{{input}}/{long}");
    assert_eq!(literal_rule(&t), Some(KeyRule::SegmentTooLong));
    let t = format!("{{input}}/{}", &long[1..]);
    assert_eq!(literal_rule(&t), None);
    // A brace pair counts as the one byte it writes.
    let t = format!("{{input}}/{}{{{{}}}}", &long[3..]);
    assert_eq!(literal_rule(&t), None);
    let t = format!("{{input}}/{}{{{{}}}}", &long[2..]);
    assert_eq!(literal_rule(&t), Some(KeyRule::SegmentTooLong));
    assert_eq!(
        check_template("{nope}", TemplateKind::Texture),
        Err(TemplateRefusal::Parse(TemplateError::Unknown(
            "nope".into()
        )))
    );
    assert_eq!(
        check_template("", TemplateKind::Texture),
        Err(TemplateRefusal::Parse(TemplateError::Empty))
    );
}

/// A member path takes no `reserved_prefix` or `reserved_name` (4.7), in
/// its literals either.
#[test]
fn a_member_template_skips_the_reserved_rules() {
    for t in ["_unityrs/{atlas}", "_unityrs", "{atlas}/.unityrs-tmp-x"] {
        assert!(check_template(t, TemplateKind::AtlasJson).is_err(), "{t}");
        assert_eq!(
            check_member_template(t, TemplateKind::AtlasJson),
            Ok(()),
            "{t}"
        );
    }
    assert_eq!(
        check_member_template("{atlas}//x", TemplateKind::AtlasJson),
        Err(TemplateRefusal::Literal(KeyRule::EmptySegment))
    );
}

/// A template of literals alone is one key: the literal checks refuse it
/// exactly when the key's own check breaks one of their rules, by the same
/// rule, and pass what only the rules they leave to an expansion refuse.
#[test]
fn a_literal_template_is_checked_as_its_key() {
    let parts = [
        "a",
        "/",
        ".",
        "..",
        "_unityrs",
        ".unityrs-tmp-",
        "x\u{1}",
        "{{",
        "}}",
    ];
    let checked = [
        KeyRule::LeadingSlash,
        KeyRule::TrailingSlash,
        KeyRule::EmptySegment,
        KeyRule::DotSegment,
        KeyRule::SegmentTooLong,
        KeyRule::ReservedPrefix,
        KeyRule::ReservedName,
    ];
    let mut n = 0;
    for a in parts {
        for b in parts {
            for c in parts {
                let text = format!("{a}{b}{c}");
                let key = text.replace("{{", "{").replace("}}", "}");
                // The key's rules past a control character still apply to
                // the literals: read the key without it.
                let plain = key.replace('\u{1}', "");
                let want = check(plain.as_bytes())
                    .err()
                    .filter(|r| checked.contains(r));
                assert_eq!(literal_rule(&text), want, "{text:?}");
                n += 1;
            }
        }
    }
    assert_eq!(n, 729);
}