Skip to main content

unityrs_export/ngui/
classify.rs

1//! `classify` (`docs/plans/batch.md` 2.7) as far as the cutter meets it:
2//! every error a read, a dereference, a resource read, a charge or a decode
3//! returns, to an object's skip, the input's failure or a run failure, with
4//! the reason and detail `docs/BATCH_SPEC.md` 7.3 and 9.3 name.
5//!
6//! The site rule for an `Error::Entry` inside a dereference or a resource
7//! read (the fourth carried question): it is the reading object's skip, with
8//! the innermost error's code; only selection's open of the input's own
9//! top-level rows, or the reach of its containers at registration, makes an
10//! entry's failure the input's `entry_error` ([`entry_error`]; `batch.md`
11//! 2.7). A string from the bytes is under 7.3's text rule ([`text`]).
12
13use std::collections::TryReserveError;
14
15use unityrs_core::budget::{BudgetExceeded, Reservation};
16use unityrs_core::env::DerefError;
17use unityrs_core::limits::ChargeError;
18use unityrs_core::typetree::TreeError;
19use unityrs_core::walk::{ParseError, ReadDetail};
20use unityrs_core::{Error, LimitError, LimitKind, NotFound, RawStr};
21use unityrs_meshdecode::MeshError;
22use unityrs_texture::sprite::SpriteError;
23use unityrs_texture::{DecodeError, MAX_PIXELS};
24
25/// The longest detail or reason argument, in bytes (7.3's cut).
26pub const CUT: usize = 1024;
27
28/// A reason of 9.3 and its 7.3 detail, each string taken from the bytes
29/// already under 7.3's text rule ([`text`]), and whether one was cut (the
30/// row's `cut`).
31#[derive(Clone, Debug, PartialEq, Eq, Hash)]
32pub struct Reason {
33    /// The reason: `name` or `name(argument, ...)`.
34    pub reason: String,
35    /// The detail, or none.
36    pub detail: Option<String>,
37    /// Whether the reason's argument or the detail was cut to [`CUT`] bytes.
38    pub cut: bool,
39}
40
41impl Reason {
42    /// A reason with no detail.
43    #[must_use]
44    pub fn plain(reason: impl Into<String>) -> Self {
45        Self {
46            reason: reason.into(),
47            detail: None,
48            cut: false,
49        }
50    }
51
52    /// `decode_error` with `code` as its detail.
53    #[must_use]
54    pub fn decode_error(code: impl Into<String>) -> Self {
55        Self {
56            reason: "decode_error".to_owned(),
57            detail: Some(code.into()),
58            cut: false,
59        }
60    }
61}
62
63/// Where a failure lands (2.7's classes).
64#[derive(Clone, Debug, PartialEq, Eq)]
65pub enum Class {
66    /// The object's skip: a data reason, the budget class's object-level
67    /// reasons (`budget(input)`, a meter's `limit`), or a decode's.
68    Skip(Reason),
69    /// The input fails (`budget(dependency)`, and the site rules' input
70    /// failures).
71    Input(Reason),
72    /// The run fails: `host_io`, `host_memory` or `internal`.
73    Run(Reason),
74}
75
76/// 7.3's text rule: `bytes` cut to their first [`CUT`] bytes at a code
77/// point boundary, an invalid byte counting as one code point, then each
78/// invalid byte replaced by U+FFFD; and whether it was cut. The string is
79/// allocated once, at the length [`text_len`] measures.
80#[must_use]
81pub fn text(bytes: &[u8]) -> (String, bool) {
82    let (n, _) = text_len(&[bytes]);
83    let mut out = String::with_capacity(n);
84    let cut = walk(&[bytes], |c| out.push(c));
85    (out, cut)
86}
87
88/// The text rule over `parts` read as one string (each part but the last
89/// ending at a code point boundary), each code point it keeps handed to
90/// `put`: whether it cut. Nothing is copied.
91fn walk(parts: &[&[u8]], mut put: impl FnMut(char)) -> bool {
92    let mut used = 0usize;
93    for part in parts {
94        for chunk in part.utf8_chunks() {
95            for c in chunk.valid().chars() {
96                if used + c.len_utf8() > CUT {
97                    return true;
98                }
99                used += c.len_utf8();
100                put(c);
101            }
102            for _ in chunk.invalid() {
103                if used + 1 > CUT {
104                    return true;
105                }
106                used += 1;
107                put(char::REPLACEMENT_CHARACTER);
108            }
109        }
110    }
111    false
112}
113
114/// The bytes the text rule's string of `parts` takes (an invalid byte's
115/// U+FFFD three of them, so at most 3 x [`CUT`]), and whether it cuts:
116/// measured, never made.
117#[must_use]
118pub fn text_len(parts: &[&[u8]]) -> (usize, bool) {
119    let mut n = 0usize;
120    let cut = walk(parts, |c| n += c.len_utf8());
121    (n, cut)
122}
123
124/// [`text`] of `parts` read as one string, as [`walk`] reads them, into a
125/// string reserved fallibly at exactly [`text_len`]'s length.
126///
127/// # Errors
128///
129/// The allocator's refusal of that reservation.
130pub fn try_text(parts: &[&[u8]]) -> Result<(String, bool), TryReserveError> {
131    let (n, _) = text_len(parts);
132    let mut out = String::new();
133    out.try_reserve_exact(n)?;
134    let cut = walk(parts, |c| out.push(c));
135    Ok((out, cut))
136}
137
138/// `name(<argument>)`, the argument from the bytes under [`text`].
139#[must_use]
140pub fn with_argument(name: &str, argument: &[u8]) -> Reason {
141    let (arg, cut) = text(argument);
142    Reason {
143        reason: format!("{name}({arg})"),
144        detail: None,
145        cut,
146    }
147}
148
149/// `outside_view(<name>)`, the name as given (a resource's `path` as read).
150#[must_use]
151pub fn outside_view(name: &RawStr) -> Reason {
152    with_argument("outside_view", name.as_bytes())
153}
154
155/// `outside_view(<cab>)` for a pointer's external that no file of the view
156/// holds: the CAB, what follows its path's last `/` (9.3; UnityPy's `PPtr`
157/// splits on `/` alone, so a `\` stays in the name).
158#[must_use]
159pub fn outside_view_cab(path: &RawStr) -> Reason {
160    let p = path.as_bytes();
161    let start = p.iter().rposition(|&b| b == b'/').map_or(0, |i| i + 1);
162    with_argument("outside_view", p.get(start..).unwrap_or_default())
163}
164
165fn internal() -> Class {
166    Class::Run(Reason::plain("internal"))
167}
168
169/// A limit kind's name in `limit(<kind>, ..)` (9.3's table).
170#[must_use]
171pub fn limit_kind(kind: LimitKind) -> Option<&'static str> {
172    Some(match kind {
173        LimitKind::InputMemory => "input_memory",
174        LimitKind::InputBytes => "input_bytes",
175        LimitKind::DecodeWork => "decode_work",
176        LimitKind::BlockOutput => "block_output",
177        LimitKind::Inflate => "inflate",
178        LimitKind::ContainerDepth => "container_depth",
179        LimitKind::TreeDepth => "tree_depth",
180        LimitKind::ValueDepth => "value_depth",
181        LimitKind::ValuesPerObject => "values_per_object",
182        LimitKind::ZeroSizeElements => "zero_size_elements",
183        LimitKind::Count => "count",
184        _ => return None,
185    })
186}
187
188/// A limit: `limit(<kind>, <configured value>)`, an object's skip whether
189/// its kind is the budget class's or data (2.7: both at the same sites).
190#[must_use]
191pub fn limit(l: &LimitError) -> Class {
192    match limit_kind(l.kind()) {
193        Some(kind) => Class::Skip(Reason::plain(format!("limit({kind}, {})", l.max()))),
194        None => internal(),
195    }
196}
197
198/// A budget's refusal: the input's own is an object's skip; a dependency's
199/// fails the input (2.6 step 7); a provider's, which no input owns, is the
200/// allocator's (`host_memory`).
201#[must_use]
202pub fn budget(b: &BudgetExceeded) -> Class {
203    match b.what {
204        Reservation::Input => Class::Skip(Reason::plain("budget(input)")),
205        Reservation::Dependency => Class::Input(Reason::plain("budget(dependency)")),
206        Reservation::Provider => Class::Run(Reason::plain("host_memory")),
207    }
208}
209
210/// A refused charge.
211#[must_use]
212pub fn charge(c: &ChargeError) -> Class {
213    match c {
214        ChargeError::Limit(l) => limit(l),
215        ChargeError::Budget(b) => budget(b),
216        ChargeError::Allocator(_) => Class::Run(Reason::plain("host_memory")),
217        _ => Class::Run(Reason::plain("internal")),
218    }
219}
220
221/// A tree's failure: rows that make no tree are `tree` (the first carried
222/// question: 7.3 lists the code, and the core's `TreeError` is it).
223#[must_use]
224pub fn tree(t: &TreeError) -> Class {
225    match t {
226        TreeError::Empty | TreeError::LevelUnderflow { .. } | TreeError::TooManyNodes(_) => {
227            Class::Skip(Reason::decode_error("tree"))
228        }
229        TreeError::Limit(l) => limit(l),
230        TreeError::Charge(c) => charge(c),
231        _ => internal(),
232    }
233}
234
235/// A typetree read's failure.
236#[must_use]
237pub fn parse(e: &ParseError) -> Class {
238    match e {
239        ParseError::Provider(p) if p.allocator.is_some() => {
240            Class::Run(Reason::plain("host_memory"))
241        }
242        ParseError::NoTypeTree { .. } | ParseError::CheckRead { .. } | ParseError::Provider(_) => {
243            Class::Skip(Reason::decode_error("asset_bundle"))
244        }
245        ParseError::Read(r) => match &r.detail {
246            // A tree failure met during the read (a peek's, a nested
247            // compile's) is the read's, but for a limit or a charge: `tree`
248            // is only the object's own tree failing (`ParseError::Tree`, 7.3).
249            ReadDetail::Limit(l) | ReadDetail::Tree(TreeError::Limit(l)) => limit(l),
250            ReadDetail::Charge(c) | ReadDetail::Tree(TreeError::Charge(c)) => charge(c),
251            ReadDetail::Eof { .. }
252            | ReadDetail::BoostEof { .. }
253            | ReadDetail::NegativeLength(_)
254            | ReadDetail::ArrayChildren
255            | ReadDetail::PairChildren
256            | ReadDetail::NoRefTypes { .. }
257            | ReadDetail::RefTypeNotFound
258            | ReadDetail::RefTypeNoTree
259            | ReadDetail::Python(_)
260            | ReadDetail::Stream(_)
261            | ReadDetail::Tree(
262                TreeError::Empty | TreeError::LevelUnderflow { .. } | TreeError::TooManyNodes(_),
263            ) => Class::Skip(Reason::decode_error("read")),
264            _ => internal(),
265        },
266        ParseError::Tree(t) => tree(t),
267        ParseError::Deref(d) => deref(d),
268        _ => internal(),
269    }
270}
271
272/// A dereference's failure, by `DerefError` (2.7).
273#[must_use]
274pub fn deref(e: &DerefError) -> Class {
275    match e {
276        DerefError::Null
277        | DerefError::FileIdPastEnd { .. }
278        | DerefError::FileIdBelowStart { .. }
279        | DerefError::RawTarget { .. }
280        | DerefError::MissingObject { .. } => Class::Skip(Reason::plain("bad_pointer")),
281        DerefError::NotFound { path } => Class::Skip(outside_view_cab(path)),
282        DerefError::Load(e) => error(e),
283        _ => internal(),
284    }
285}
286
287/// The code of an error the bytes decide (7.3), through its wrappers.
288#[must_use]
289pub fn error(e: &Error) -> Class {
290    let code = match e {
291        Error::Entry { source, .. } => return error(source),
292        Error::AssetBundle(p) => return parse(p),
293        Error::Deref(d) => return deref(d),
294        Error::Tree(t) => return tree(t),
295        Error::Limit(l) => return limit(l),
296        Error::Budget(b) => return budget(b),
297        Error::Allocator(_) | Error::Detect(unityrs_core::detect::DetectError::Allocator(_)) => {
298            return Class::Run(Reason::plain("host_memory"));
299        }
300        Error::Io(_) => return Class::Run(Reason::plain("host_io")),
301        Error::Detect(_) => "detect",
302        Error::OutOfBounds { .. } => "out_of_bounds",
303        // BATCH_SPEC 7.3: a bad signature (wrong key) or short AES vector
304        // is corrupt input, so reuse `malformed` rather than add a code.
305        Error::Malformed { .. } | Error::UnityCnSignature | Error::UnityCnVectorLength { .. } => {
306            "malformed"
307        }
308        // Preserve the pre-UnityCN encrypted-input refusal for key problems.
309        Error::UnityCnKeyMissing | Error::UnityCnKeyLength { .. } | Error::Unsupported(_) => {
310            "unsupported"
311        }
312        Error::Decompress { .. } => "decompress",
313        Error::Version(_) => "version",
314        Error::TypeIndex { .. } => "type_index",
315        Error::NotFound(_) => "not_found",
316        _ => return internal(),
317    };
318    Class::Skip(Reason::decode_error(code))
319}
320
321/// A resource read's failure from the Environment's fallback: a resource no
322/// candidate finds is `outside_view(<path>)`, its path as read (E65).
323#[must_use]
324pub fn resource(e: &Error, path: &RawStr) -> Class {
325    match e {
326        Error::NotFound(NotFound::Resource(_)) => Class::Skip(outside_view(path)),
327        other => error(other),
328    }
329}
330
331/// A texture decode's failure (2.7's decode row; section 3's answers).
332#[must_use]
333pub fn decode(e: &DecodeError) -> Class {
334    let code = match e {
335        DecodeError::NoImageData => "no_image_data",
336        DecodeError::NegativeSize { .. } => "negative_size",
337        DecodeError::PillowMemoryError { .. } => "pillow_memory_error",
338        DecodeError::NotEnoughData { .. } => "not_enough_data",
339        DecodeError::DecompressionBomb { .. } => "decompression_bomb",
340        DecodeError::Crunch(_) => "crunch",
341        DecodeError::Hdr(_) => "malformed",
342        DecodeError::Platform(_) | DecodeError::PvrtcBlockCount => "read",
343        DecodeError::TooLarge { .. } => {
344            return Class::Skip(Reason::plain(format!(
345                "limit(texture_pixels, {MAX_PIXELS})"
346            )));
347        }
348        DecodeError::Charge(c) => return charge(c),
349        DecodeError::Panicked { payload } => return panicked(payload),
350        _ => return internal(),
351    };
352    Class::Skip(Reason::decode_error(code))
353}
354
355/// A contained panic: `decoder_panic`, its payload the detail. The payload
356/// is cut where the panic was contained, to `MESSAGE_BYTES` (1,024) at a
357/// code point boundary: its flag is the row's `cut`.
358fn panicked(payload: &unityrs_texture::Payload) -> Class {
359    Class::Skip(Reason {
360        reason: "decoder_panic".to_owned(),
361        detail: Some(payload.message().to_owned()),
362        cut: payload.is_cut(),
363    })
364}
365
366/// A Sprite's render failure (E17; 7.3's codes for a Sprite): Pillow's
367/// refusals of a crop or an image as an atlas crop's are named
368/// (`decompression_bomb`, `crop_overflow` for a box edge outside a C
369/// `int` or `long`, `pillow_memory_error` for an image wider than Pillow
370/// makes), a field of another shape is `read` (4.4 step 2's rule), a
371/// sheet of a mode the renderer is not verified on `unsupported` (as a
372/// mesh part left to a later phase is), a canvas past the renderer's bound is `limit(texture_pixels, ..)` as a
373/// texture's is, a refused charge or work count is its own class, and a
374/// panic `decoder_panic`; every other exception UnityPy 1.25.2's
375/// `SpriteHelper` raises is `render`.
376#[must_use]
377pub fn render(e: &SpriteError) -> Class {
378    let code = match e {
379        SpriteError::DecompressionBomb { .. } => "decompression_bomb",
380        SpriteError::CIntOverflow { .. } | SpriteError::CLongOverflow => "crop_overflow",
381        SpriteError::ImageTooWide => "pillow_memory_error",
382        SpriteError::Malformed(_) => "read",
383        SpriteError::UnverifiedMode { .. } => "unsupported",
384        SpriteError::AtlasUnresolved => return Class::Skip(Reason::plain("bad_pointer")),
385        SpriteError::TooLarge { .. } => {
386            return Class::Skip(Reason::plain(format!(
387                "limit(texture_pixels, {MAX_PIXELS})"
388            )));
389        }
390        SpriteError::Charge(c) => return charge(c),
391        SpriteError::Panicked(payload) => return panicked(payload),
392        SpriteError::Mesh(m) => return mesh(m),
393        SpriteError::CropRightLeft
394        | SpriteError::CropLowerUpper
395        | SpriteError::RoundNan
396        | SpriteError::RoundInfinity
397        | SpriteError::SolveCast
398        | SpriteError::Rotation(_)
399        | SpriteError::AlphaSizeMismatch
400        | SpriteError::AlphaBandCount
401        | SpriteError::NoVertices
402        | SpriteError::Unpack { .. }
403        | SpriteError::Index { .. }
404        | SpriteError::Sprite3d
405        | SpriteError::NoTriangles
406        | SpriteError::NegativeSize
407        | SpriteError::NoAtlasData => "render",
408        _ => return internal(),
409    };
410    Class::Skip(Reason::decode_error(code))
411}
412
413/// A Sprite's mesh failure (E16 inside E17): a refused charge or work count
414/// is its own class, a part `unityrs-meshdecode` leaves to a later phase
415/// `unsupported`, a field of another shape `read`, and every exception
416/// UnityPy's `MeshHandler` raises `render`, as the render's own.
417fn mesh(e: &MeshError) -> Class {
418    let code = match e {
419        MeshError::Charge(c) => return charge(c),
420        MeshError::Resource(e) => return error(e),
421        MeshError::Unsupported(_) => "unsupported",
422        MeshError::Malformed(_) => "read",
423        MeshError::Assertion(_)
424        | MeshError::NoAttribute(_)
425        | MeshError::UnknownMeshType
426        | MeshError::VersionType(_)
427        | MeshError::InvalidFormat { .. }
428        | MeshError::UnknownChannel(_)
429        | MeshError::NoChannels
430        | MeshError::OutOfBounds
431        | MeshError::Struct(_)
432        | MeshError::Index(_)
433        | MeshError::Unpack { .. }
434        | MeshError::ByteRange
435        | MeshError::Topology
436        | MeshError::WrappedAccess => "render",
437        _ => return internal(),
438    };
439    Class::Skip(Reason::decode_error(code))
440}
441
442/// Selection's open of a top-level row of the input that fails: the input's
443/// `entry_error`, its detail the code, a space and the row's path, the whole
444/// cut to [`CUT`] bytes, written by the text rule from the three parts in
445/// place, so the path is never copied whole (review round 3's P2); a class
446/// other than a code (a budget, a stop) stays what it is, the input's or
447/// the run's.
448#[must_use]
449pub fn entry_error(e: &Error, path: &RawStr) -> Class {
450    match error(e) {
451        Class::Skip(r) if r.reason == "decode_error" => {
452            let code = r.detail.unwrap_or_default();
453            // The code is ASCII, so each part but the path ends at a code
454            // point boundary.
455            let parts = [code.as_bytes(), b" ".as_slice(), path.as_bytes()];
456            let Ok((detail, cut)) = try_text(&parts) else {
457                return Class::Run(Reason::plain("host_memory"));
458            };
459            Class::Input(Reason {
460                reason: "entry_error".to_owned(),
461                detail: Some(detail),
462                cut,
463            })
464        }
465        Class::Skip(r) => Class::Input(r),
466        other => other,
467    }
468}
469
470/// Whether a prepared unsupported-format argument is a pinned format name.
471#[must_use]
472pub fn known_texture_format(name: &str) -> bool {
473    unityrs_texture::TEXTURE_FORMATS
474        .iter()
475        .any(|(_, n)| *n == name)
476}
477
478#[cfg(test)]
479mod tests {
480    use std::sync::Arc;
481
482    use unityrs_core::budget::{BudgetExceeded, Reservation};
483    use unityrs_core::env::DerefError;
484    use unityrs_core::typetree::TreeError;
485    use unityrs_core::walk::{ParseError, ReadDetail, ReadError, ReadErrorKind};
486    use unityrs_core::{Error, LimitError, LimitKind, NotFound, RawStr};
487    use unityrs_texture::DecodeError;
488
489    use super::{Class, Reason, entry_error, error, parse, resource, text, text_len, try_text};
490
491    fn skip(reason: &str, detail: Option<&str>) -> Class {
492        Class::Skip(Reason {
493            reason: reason.to_owned(),
494            detail: detail.map(str::to_owned),
495            cut: false,
496        })
497    }
498
499    fn read(detail: ReadDetail) -> ParseError {
500        ParseError::Read(ReadError {
501            kind: ReadErrorKind::Other,
502            at: 0,
503            detail,
504        })
505    }
506
507    #[test]
508    fn each_wrapper_reaches_the_innermost_code() {
509        let malformed = Error::Malformed {
510            what: "x",
511            detail: "y".into(),
512        };
513        let entry = Error::Entry {
514            name: RawStr::from(b"CAB-a".as_slice()),
515            source: Arc::new(malformed.clone()),
516        };
517        let load = Error::Deref(Arc::new(DerefError::Load(entry.clone())));
518        let in_parse =
519            Error::AssetBundle(Arc::new(ParseError::Deref(DerefError::Load(load.clone()))));
520        for e in [&malformed, &entry, &load, &in_parse] {
521            assert_eq!(error(e), skip("decode_error", Some("malformed")), "{e}");
522        }
523        let missing = DerefError::NotFound {
524            path: RawStr::from(b"archive:/CAB-z/CAB-z".as_slice()),
525        };
526        assert_eq!(
527            error(&Error::Deref(Arc::new(missing))),
528            skip("outside_view(CAB-z)", None)
529        );
530        assert_eq!(
531            error(&Error::Deref(Arc::new(DerefError::Null))),
532            skip("bad_pointer", None)
533        );
534    }
535
536    #[test]
537    fn parse_errors_take_their_codes_and_limits_their_kinds() {
538        let tree = TreeError::LevelUnderflow { row: 1, level: 3 };
539        assert_eq!(
540            parse(&ParseError::Tree(tree.clone())),
541            skip("decode_error", Some("tree"))
542        );
543        assert_eq!(
544            parse(&read(ReadDetail::Tree(tree))),
545            skip("decode_error", Some("read"))
546        );
547        assert_eq!(
548            parse(&read(ReadDetail::Eof {
549                need: 4,
550                exception: "EOFError"
551            })),
552            skip("decode_error", Some("read"))
553        );
554        assert_eq!(
555            parse(&read(ReadDetail::BoostEof {
556                method: "read_i32",
557                need: 4,
558                exception: "EOFError",
559            })),
560            skip("decode_error", Some("read"))
561        );
562        let depth = LimitError::refused(LimitKind::ValueDepth, 600, 512);
563        assert_eq!(
564            parse(&read(ReadDetail::Limit(depth))),
565            skip("limit(value_depth, 512)", None)
566        );
567        assert_eq!(
568            parse(&ParseError::NoTypeTree {
569                class_id: 28,
570                why: None
571            }),
572            skip("decode_error", Some("asset_bundle"))
573        );
574        let dep = BudgetExceeded {
575            requested: 1,
576            what: Reservation::Dependency,
577        };
578        assert_eq!(
579            error(&Error::Budget(dep)),
580            Class::Input(Reason::plain("budget(dependency)"))
581        );
582        let input = BudgetExceeded {
583            requested: 1,
584            what: Reservation::Input,
585        };
586        assert_eq!(error(&Error::Budget(input)), skip("budget(input)", None));
587    }
588
589    #[test]
590    fn a_missing_resource_names_its_path_and_a_decode_its_code() {
591        let path = RawStr::from(b"archive:/CAB-x/r.resS".as_slice());
592        let e = Error::NotFound(NotFound::Resource(RawStr::from(b"r.resS".as_slice())));
593        assert_eq!(
594            resource(&e, &path),
595            skip("outside_view(archive:/CAB-x/r.resS)", None)
596        );
597        assert_eq!(
598            super::decode(&DecodeError::TooLarge { pixels: 1, max: 1 }),
599            skip("limit(texture_pixels, 268435456)", None)
600        );
601        assert_eq!(
602            super::decode(&DecodeError::NegativeSize {
603                width: -1,
604                height: 1
605            }),
606            skip("decode_error", Some("negative_size"))
607        );
608    }
609
610    #[test]
611    fn malformed_crunch_is_an_object_decode_skip() {
612        let e = DecodeError::Crunch(unityrs_texture::CrunchError::Header("signature"));
613        assert_eq!(super::decode(&e), skip("decode_error", Some("crunch")));
614    }
615
616    #[test]
617    fn every_hdr_content_error_is_a_malformed_object_skip() {
618        use unityrs_texture::HdrError;
619
620        for error in [HdrError::ReservedMode, HdrError::InvalidBlock] {
621            assert_eq!(
622                super::decode(&DecodeError::Hdr(error)),
623                skip("decode_error", Some("malformed"))
624            );
625        }
626    }
627
628    #[test]
629    fn an_open_of_an_own_row_is_the_inputs_entry_error() {
630        let e = Error::Unsupported(unityrs_core::Unsupported::WebFile);
631        let got = entry_error(&e, &RawStr::from(b"web.data".as_slice()));
632        assert_eq!(
633            got,
634            Class::Input(Reason {
635                reason: "entry_error".to_owned(),
636                detail: Some("unsupported web.data".to_owned()),
637                cut: false,
638            })
639        );
640        let long = vec![b'a'; 2000];
641        let Class::Input(r) = entry_error(&e, &RawStr::from(long.as_slice())) else {
642            panic!("an input failure");
643        };
644        assert_eq!((r.detail.map(|d| d.len()), r.cut), (Some(1024), true));
645    }
646
647    #[test]
648    fn text_is_cut_by_its_bytes_then_each_invalid_byte_replaced() {
649        // A truncated sequence is two invalid bytes, two U+FFFDs (review
650        // round 1: the lossy decoding gave one).
651        assert_eq!(text(b"\xe2\x82"), ("\u{fffd}\u{fffd}".to_owned(), false));
652        assert_eq!(text(b"a\xffb"), ("a\u{fffd}b".to_owned(), false));
653        // 1,024 bytes are kept whole; 1,025 are cut, and say so.
654        let a = |n| vec![b'a'; n];
655        assert_eq!(text(&a(1024)), ("a".repeat(1024), false));
656        assert_eq!(text(&a(1025)), ("a".repeat(1024), true));
657        // A code point is never split: 1,023 bytes and a two-byte one.
658        let mut split = a(1023);
659        split.extend_from_slice("é".as_bytes());
660        assert_eq!(text(&split), ("a".repeat(1023), true));
661        // 500 invalid bytes are 500 code points, under the cut, each 3 bytes
662        // once replaced.
663        let (t, cut) = text(&[0xff; 500]);
664        assert_eq!((t.chars().count(), t.len(), cut), (500, 1500, false));
665        let (t, cut) = text(&[0xff; 1025]);
666        assert_eq!((t.chars().count(), cut), (1024, true));
667    }
668
669    #[test]
670    fn the_text_rule_is_measured_then_made_at_that_length() {
671        // Review round 3's P2: 1,024 invalid bytes are 3,072 bytes of
672        // U+FFFD, measured before anything is made, and made at exactly
673        // that capacity; parts read as one string.
674        assert_eq!(text_len(&[&[0xff; 1100]]), (3072, true));
675        let (t, cut) = try_text(&[&[0xff; 1024]]).unwrap();
676        assert_eq!((t.len(), t.capacity(), cut), (3072, 3072, false));
677        let path = vec![b'p'; 30_000];
678        let parts: [&[u8]; 3] = [b"unsupported", b" ", &path];
679        assert_eq!(text_len(&parts), (1024, true));
680        let (t, cut) = try_text(&parts).unwrap();
681        assert_eq!((&t[..13], t.len(), cut), ("unsupported p", 1024, true));
682        // A long path's `entry_error` keeps its first 1,024 bytes.
683        let e = Error::Unsupported(unityrs_core::Unsupported::WebFile);
684        let path = RawStr::from(vec![b'q'; 30_000]);
685        let Class::Input(r) = entry_error(&e, &path) else {
686            panic!("an input failure");
687        };
688        assert_eq!(r.detail.map(|d| d.len()), Some(1024));
689    }
690
691    #[test]
692    fn an_outside_view_pointer_names_its_cabs_basename() {
693        let path = RawStr::from(b"archive:/CAB-x/CAB-x".as_slice());
694        let got = super::deref(&DerefError::NotFound { path });
695        assert_eq!(got, skip("outside_view(CAB-x)", None));
696        let long = RawStr::from(vec![b'p'; 1100]);
697        let Class::Skip(r) = super::deref(&DerefError::NotFound { path: long }) else {
698            panic!("a skip");
699        };
700        assert!(r.cut);
701        assert_eq!(r.reason.len(), "outside_view()".len() + 1024);
702        // Split on `/` alone, as UnityPy's `PPtr` splits (review round 2's
703        // C8): a backslash is part of the name.
704        let path = RawStr::from(b"archive:/CAB-a\\b".as_slice());
705        let got = super::deref(&DerefError::NotFound { path });
706        assert_eq!(got, skip("outside_view(CAB-a\\b)", None));
707        let path = RawStr::from(b"CAB-c".as_slice());
708        let got = super::deref(&DerefError::NotFound { path });
709        assert_eq!(got, skip("outside_view(CAB-c)", None));
710    }
711
712    #[test]
713    fn a_contained_panic_is_decoder_panic_with_its_cut() {
714        // Review round 2's T3: through `unityrs_texture::contain`, as the
715        // decoders' panics come.
716        let panicked = |f: fn()| {
717            let e = unityrs_texture::contain(|| -> Result<(), DecodeError> {
718                f();
719                Ok(())
720            })
721            .unwrap_err();
722            let Class::Skip(r) = super::decode(&e) else {
723                panic!("a skip");
724            };
725            assert_eq!(r.reason, "decoder_panic");
726            (r.detail.unwrap_or_default(), r.cut)
727        };
728        let short = panicked(|| panic!("short"));
729        let long = panicked(|| panic!("{}\u{e9}", "a".repeat(1023)));
730        let other = panicked(|| std::panic::panic_any(7u32));
731        assert_eq!(short, ("short".to_owned(), false));
732        // 1,023 bytes and a two-byte character: cut before it.
733        assert_eq!(long, ("a".repeat(1023), true));
734        assert_eq!(
735            other,
736            (unityrs_texture::NON_STRING_PAYLOAD.to_owned(), false)
737        );
738    }
739
740    #[test]
741    fn a_tree_failure_inside_a_read_is_read_and_the_objects_own_is_tree() {
742        assert_eq!(
743            parse(&read(ReadDetail::Tree(TreeError::Empty))),
744            skip("decode_error", Some("read"))
745        );
746        assert_eq!(
747            parse(&ParseError::Tree(TreeError::Empty)),
748            skip("decode_error", Some("tree"))
749        );
750    }
751}