ltk_meta 0.9.1

Metadata formats and utilities for League Toolkit
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
//! [`ValueView`]: the borrowed mirror of [`PropertyValueEnum`](crate::PropertyValueEnum).
//!
//! Leaves carry decoded primitives — a `&'a str` for a string, validated on the way out —
//! and complex kinds carry sub-views that descend further, still zero-copy, to any depth.
//! `Elements[3].Position` is one [`ContainerView::get`] and two [`StructView::property`] calls,
//! and no sibling of anything on that path is ever looked at.

use std::fmt;

use glam::{Mat4, Vec2, Vec3, Vec4};
use ltk_hash::{BinHash, HashValue, WadHash};
use ltk_primitives::Color;

use crate::{
    property::Kind,
    stream::{
        layout::Cursor,
        view::{copy_views, find_property, Properties, PropertyView},
    },
    Error,
};

/// A borrowed, lazily-decoded value: one variant per [`Kind`].
///
/// Read with [`PropertyView::value_view`], or from a sub-view's iterator. The owned mirror is
/// [`PropertyValueEnum`](crate::PropertyValueEnum), one call away through
/// [`PropertyView::value`].
pub enum ValueView<'a> {
    /// [`Kind::None`]: no bytes at all.
    None,
    /// [`Kind::Bool`].
    Bool(bool),
    /// [`Kind::I8`].
    I8(i8),
    /// [`Kind::U8`].
    U8(u8),
    /// [`Kind::I16`].
    I16(i16),
    /// [`Kind::U16`].
    U16(u16),
    /// [`Kind::I32`].
    I32(i32),
    /// [`Kind::U32`].
    U32(u32),
    /// [`Kind::I64`].
    I64(i64),
    /// [`Kind::U64`].
    U64(u64),
    /// [`Kind::F32`].
    F32(f32),
    /// [`Kind::Vector2`].
    Vector2(Vec2),
    /// [`Kind::Vector3`].
    Vector3(Vec3),
    /// [`Kind::Vector4`].
    Vector4(Vec4),
    /// [`Kind::Matrix44`], stored row by row on the wire.
    Matrix44(Mat4),
    /// [`Kind::Color`], four RGBA bytes.
    Color(Color<u8>),
    /// [`Kind::String`], borrowed from the buffered object.
    String(&'a str),
    /// [`Kind::Hash`]. The value includes its stored width.
    Hash(HashValue),
    /// [`Kind::WadChunkLink`].
    WadChunkLink(WadHash),
    /// [`Kind::ObjectLink`].
    ObjectLink(BinHash),
    /// [`Kind::BitBool`].
    BitBool(bool),
    /// [`Kind::Container`].
    Container(ContainerView<'a>),
    /// [`Kind::UnorderedContainer`].
    UnorderedContainer(ContainerView<'a>),
    /// [`Kind::Optional`].
    Optional(OptionalView<'a>),
    /// [`Kind::Map`].
    Map(MapView<'a>),
    /// [`Kind::Struct`] — a pointer, whose class hash is `0` when it is null.
    Struct(StructView<'a>),
    /// [`Kind::Embedded`].
    Embedded(StructView<'a>),
}

impl<'a> ValueView<'a> {
    /// Reads one value of `kind`, advancing `cur` past exactly that value.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidPropertyTypePrimitive`] for a kind byte that does not decode,
    /// [`Error::InvalidNesting`] or [`Error::InvalidKeyType`] for a container the value model
    /// refuses, [`Error::Utf8Error`] for a string that is not UTF-8, or [`Error::IOError`] at
    /// the end of the slice.
    pub(crate) fn read(cur: &mut Cursor<'a>, kind: Kind) -> Result<Self, Error> {
        use Kind as K;
        Ok(match kind {
            K::None => Self::None,
            K::Bool => Self::Bool(cur.bool()?),
            K::BitBool => Self::BitBool(cur.bool()?),
            K::I8 => Self::I8(cur.i8()?),
            K::U8 => Self::U8(cur.u8()?),
            K::I16 => Self::I16(cur.i16()?),
            K::U16 => Self::U16(cur.u16()?),
            K::I32 => Self::I32(cur.i32()?),
            K::U32 => Self::U32(cur.u32()?),
            K::I64 => Self::I64(cur.i64()?),
            K::U64 => Self::U64(cur.u64()?),
            K::F32 => Self::F32(cur.f32()?),
            K::Vector2 => Self::Vector2(cur.vec2()?),
            K::Vector3 => Self::Vector3(cur.vec3()?),
            K::Vector4 => Self::Vector4(cur.vec4()?),
            K::Matrix44 => Self::Matrix44(cur.mat4_row_major()?),
            K::Color => Self::Color(cur.color_u8()?),
            K::String => Self::String(cur.str_u16()?),
            K::Hash => Self::Hash(cur.hash_value()?),
            K::WadChunkLink => Self::WadChunkLink(cur.wad_hash()?),
            K::ObjectLink => Self::ObjectLink(cur.bin_hash()?),
            K::Container => Self::Container(ContainerView::read(cur)?),
            K::UnorderedContainer => Self::UnorderedContainer(ContainerView::read(cur)?),
            K::Optional => Self::Optional(OptionalView::read(cur)?),
            K::Map => Self::Map(MapView::read(cur)?),
            K::Struct => Self::Struct(StructView::read(cur)?),
            K::Embedded => Self::Embedded(StructView::read(cur)?),
        })
    }

    /// The kind this value is.
    #[must_use]
    pub fn kind(&self) -> Kind {
        match self {
            Self::None => Kind::None,
            Self::Bool(_) => Kind::Bool,
            Self::I8(_) => Kind::I8,
            Self::U8(_) => Kind::U8,
            Self::I16(_) => Kind::I16,
            Self::U16(_) => Kind::U16,
            Self::I32(_) => Kind::I32,
            Self::U32(_) => Kind::U32,
            Self::I64(_) => Kind::I64,
            Self::U64(_) => Kind::U64,
            Self::F32(_) => Kind::F32,
            Self::Vector2(_) => Kind::Vector2,
            Self::Vector3(_) => Kind::Vector3,
            Self::Vector4(_) => Kind::Vector4,
            Self::Matrix44(_) => Kind::Matrix44,
            Self::Color(_) => Kind::Color,
            Self::String(_) => Kind::String,
            Self::Hash(_) => Kind::Hash,
            Self::WadChunkLink(_) => Kind::WadChunkLink,
            Self::ObjectLink(_) => Kind::ObjectLink,
            Self::BitBool(_) => Kind::BitBool,
            Self::Container(_) => Kind::Container,
            Self::UnorderedContainer(_) => Kind::UnorderedContainer,
            Self::Optional(_) => Kind::Optional,
            Self::Map(_) => Kind::Map,
            Self::Struct(_) => Kind::Struct,
            Self::Embedded(_) => Kind::Embedded,
        }
    }
}

impl fmt::Debug for ValueView<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        macro_rules! leaf {
            ($name:literal, $value:expr) => {
                f.debug_tuple($name).field($value).finish()
            };
        }
        match self {
            Self::None => f.write_str("None"),
            Self::Bool(v) => leaf!("Bool", v),
            Self::I8(v) => leaf!("I8", v),
            Self::U8(v) => leaf!("U8", v),
            Self::I16(v) => leaf!("I16", v),
            Self::U16(v) => leaf!("U16", v),
            Self::I32(v) => leaf!("I32", v),
            Self::U32(v) => leaf!("U32", v),
            Self::I64(v) => leaf!("I64", v),
            Self::U64(v) => leaf!("U64", v),
            Self::F32(v) => leaf!("F32", v),
            Self::Vector2(v) => leaf!("Vector2", v),
            Self::Vector3(v) => leaf!("Vector3", v),
            Self::Vector4(v) => leaf!("Vector4", v),
            Self::Matrix44(v) => leaf!("Matrix44", v),
            Self::Color(v) => leaf!("Color", v),
            Self::String(v) => leaf!("String", v),
            Self::Hash(v) => leaf!("Hash", v),
            Self::WadChunkLink(v) => leaf!("WadChunkLink", v),
            Self::ObjectLink(v) => leaf!("ObjectLink", v),
            Self::BitBool(v) => leaf!("BitBool", v),
            Self::Container(v) => leaf!("Container", v),
            Self::UnorderedContainer(v) => leaf!("UnorderedContainer", v),
            Self::Optional(v) => leaf!("Optional", v),
            Self::Map(v) => leaf!("Map", v),
            Self::Struct(v) => leaf!("Struct", v),
            Self::Embedded(v) => leaf!("Embedded", v),
        }
    }
}

/// A [`Kind::Container`] or [`Kind::UnorderedContainer`], viewed in place.
pub struct ContainerView<'a> {
    item_kind: Kind,
    len: u32,
    /// Positioned at the first item.
    items: Cursor<'a>,
}

impl<'a> ContainerView<'a> {
    fn read(cur: &mut Cursor<'a>) -> Result<Self, Error> {
        let item_kind = cur.item_kind()?;

        let size = cur.u32()? as usize;
        let mut items = cur.sub(size)?;
        let len = items.u32()?;

        Ok(Self {
            item_kind,
            len,
            items,
        })
    }

    /// The kind every item has.
    #[must_use]
    pub fn item_kind(&self) -> Kind {
        self.item_kind
    }

    /// How many items the container declares.
    #[must_use]
    pub fn len(&self) -> u32 {
        self.len
    }

    /// Whether the container declares no items.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// The cursor at each item, in order, with nothing decoded.
    ///
    /// The iterator skips each item by its declared width or its counts, the same walk
    /// [`ContainerItems`] runs, and reads no item.
    pub(crate) fn cursors(&self) -> ItemCursors<'a> {
        ItemCursors {
            cur: self.items,
            remaining: self.len,
            item_kind: self.item_kind,
        }
    }

    /// The items, in order.
    pub fn iter(&self) -> ContainerItems<'a> {
        ContainerItems {
            cur: self.items,
            remaining: self.len,
            item_kind: self.item_kind,
        }
    }

    /// The item at `index`.
    ///
    /// One offset calculation for a fixed-width item kind; a walk over the items before it
    /// for a string, a struct or an embed.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidPropertyTypePrimitive`] for a kind byte that does not decode,
    /// [`Error::InvalidNesting`] or [`Error::InvalidKeyType`] for a value the model refuses,
    /// [`Error::Utf8Error`] for a string that is not UTF-8, or [`Error::IOError`] if the
    /// container's bytes end early.
    pub fn get(&self, index: u32) -> Result<Option<ValueView<'a>>, Error> {
        if index >= self.len {
            return Ok(None);
        }

        let mut cur = self.items;
        // All `Hash` items of one container have the same width. `cur` is at the first item.
        let width = match self.item_kind {
            Kind::Hash => Some(cur.hash_width().bytes()),
            kind => kind.fixed_width(),
        };
        match width {
            // Saturating is safe because `skip` refuses a distance it cannot add to its own
            // position: an offset too large to represent lands on the end-of-slice error a
            // walk to it would have raised, rather than wrapping around to a real position.
            Some(width) => cur.skip(width.saturating_mul(index as usize))?,
            None => {
                for _ in 0..index {
                    cur.skip_value(self.item_kind)?;
                }
            }
        }

        ValueView::read(&mut cur, self.item_kind).map(Some)
    }
}

impl<'a> IntoIterator for &ContainerView<'a> {
    type Item = Result<ValueView<'a>, Error>;
    type IntoIter = ContainerItems<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl fmt::Debug for ContainerView<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ContainerView")
            .field("item_kind", &self.item_kind)
            .field("len", &self.len)
            .finish()
    }
}

/// Iterator over the cursor at each item of a [`ContainerView`], decoding none of them.
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[derive(Debug, Clone, Copy)]
pub(crate) struct ItemCursors<'a> {
    cur: Cursor<'a>,
    remaining: u32,
    item_kind: Kind,
}

impl<'a> Iterator for ItemCursors<'a> {
    type Item = Result<Cursor<'a>, Error>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }
        self.remaining -= 1;

        let at = self.cur;
        Some(match self.cur.skip_value(self.item_kind) {
            Ok(()) => Ok(at),
            Err(error) => {
                self.remaining = 0;
                Err(error)
            }
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining as usize, Some(self.remaining as usize))
    }
}

impl std::iter::FusedIterator for ItemCursors<'_> {}

/// Iterator over the cursor at each key and value of a [`MapView`], decoding none of them.
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[derive(Debug, Clone, Copy)]
pub(crate) struct EntryCursors<'a> {
    cur: Cursor<'a>,
    remaining: u32,
    key_kind: Kind,
    value_kind: Kind,
}

impl<'a> EntryCursors<'a> {
    fn skip_entry(&mut self) -> Result<(Cursor<'a>, Cursor<'a>), Error> {
        let key = self.cur;
        self.cur.skip_value(self.key_kind)?;
        let value = self.cur;
        self.cur.skip_value(self.value_kind)?;
        Ok((key, value))
    }
}

impl<'a> Iterator for EntryCursors<'a> {
    type Item = Result<(Cursor<'a>, Cursor<'a>), Error>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }
        self.remaining -= 1;

        Some(match self.skip_entry() {
            Ok(entry) => Ok(entry),
            Err(error) => {
                self.remaining = 0;
                Err(error)
            }
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining as usize, Some(self.remaining as usize))
    }
}

impl std::iter::FusedIterator for EntryCursors<'_> {}

/// Iterator over the items of a [`ContainerView`].
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct ContainerItems<'a> {
    cur: Cursor<'a>,
    remaining: u32,
    item_kind: Kind,
}

impl<'a> Iterator for ContainerItems<'a> {
    type Item = Result<ValueView<'a>, Error>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }
        self.remaining -= 1;

        Some(match ValueView::read(&mut self.cur, self.item_kind) {
            Ok(value) => Ok(value),
            Err(error) => {
                self.remaining = 0;
                Err(error)
            }
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining as usize, Some(self.remaining as usize))
    }
}

impl std::iter::FusedIterator for ContainerItems<'_> {}

impl Clone for ContainerItems<'_> {
    fn clone(&self) -> Self {
        Self {
            cur: self.cur,
            remaining: self.remaining,
            item_kind: self.item_kind,
        }
    }
}

impl fmt::Debug for ContainerItems<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ContainerItems")
            .field("item_kind", &self.item_kind)
            .field("remaining", &self.remaining)
            .finish()
    }
}

/// A [`Kind::Map`], viewed in place.
pub struct MapView<'a> {
    key_kind: Kind,
    value_kind: Kind,
    len: u32,
    /// Positioned at the first entry.
    entries: Cursor<'a>,
}

impl<'a> MapView<'a> {
    fn read(cur: &mut Cursor<'a>) -> Result<Self, Error> {
        let key_kind = cur.key_kind()?;
        let value_kind = cur.item_kind()?;

        let size = cur.u32()? as usize;
        let mut entries = cur.sub(size)?;
        let len = entries.u32()?;

        Ok(Self {
            key_kind,
            value_kind,
            len,
            entries,
        })
    }

    /// The kind every key has.
    #[must_use]
    pub fn key_kind(&self) -> Kind {
        self.key_kind
    }

    /// The kind every value has.
    #[must_use]
    pub fn value_kind(&self) -> Kind {
        self.value_kind
    }

    /// How many entries the map declares.
    #[must_use]
    pub fn len(&self) -> u32 {
        self.len
    }

    /// Whether the map declares no entries.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// The cursor at each key and value, in file order, with nothing decoded.
    pub(crate) fn cursors(&self) -> EntryCursors<'a> {
        EntryCursors {
            cur: self.entries,
            remaining: self.len,
            key_kind: self.key_kind,
            value_kind: self.value_kind,
        }
    }

    /// The entries, in file order.
    pub fn iter(&self) -> MapEntries<'a> {
        MapEntries {
            cur: self.entries,
            remaining: self.len,
            key_kind: self.key_kind,
            value_kind: self.value_kind,
        }
    }
}

impl<'a> IntoIterator for &MapView<'a> {
    type Item = Result<(ValueView<'a>, ValueView<'a>), Error>;
    type IntoIter = MapEntries<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl fmt::Debug for MapView<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MapView")
            .field("key_kind", &self.key_kind)
            .field("value_kind", &self.value_kind)
            .field("len", &self.len)
            .finish()
    }
}

/// Iterator over the entries of a [`MapView`].
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct MapEntries<'a> {
    cur: Cursor<'a>,
    remaining: u32,
    key_kind: Kind,
    value_kind: Kind,
}

impl<'a> MapEntries<'a> {
    fn read_entry(&mut self) -> Result<(ValueView<'a>, ValueView<'a>), Error> {
        let key = ValueView::read(&mut self.cur, self.key_kind)?;
        let value = ValueView::read(&mut self.cur, self.value_kind)?;
        Ok((key, value))
    }
}

impl<'a> Iterator for MapEntries<'a> {
    type Item = Result<(ValueView<'a>, ValueView<'a>), Error>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }
        self.remaining -= 1;

        Some(match self.read_entry() {
            Ok(entry) => Ok(entry),
            Err(error) => {
                self.remaining = 0;
                Err(error)
            }
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining as usize, Some(self.remaining as usize))
    }
}

impl std::iter::FusedIterator for MapEntries<'_> {}

impl Clone for MapEntries<'_> {
    fn clone(&self) -> Self {
        Self {
            cur: self.cur,
            remaining: self.remaining,
            key_kind: self.key_kind,
            value_kind: self.value_kind,
        }
    }
}

impl fmt::Debug for MapEntries<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MapEntries")
            .field("key_kind", &self.key_kind)
            .field("value_kind", &self.value_kind)
            .field("remaining", &self.remaining)
            .finish()
    }
}

/// A [`Kind::Optional`], viewed in place.
pub struct OptionalView<'a> {
    item_kind: Kind,
    /// Positioned at the value, when there is one.
    value: Option<Cursor<'a>>,
}

impl<'a> OptionalView<'a> {
    fn read(cur: &mut Cursor<'a>) -> Result<Self, Error> {
        let item_kind = cur.item_kind()?;

        let value = match cur.bool()? {
            true => Some(cur.sub_value(item_kind)?),
            false => None,
        };

        Ok(Self { item_kind, value })
    }

    /// The kind of the item, present or not — the wire declares it either way.
    #[must_use]
    pub fn item_kind(&self) -> Kind {
        self.item_kind
    }

    /// Whether a value is present.
    #[must_use]
    pub fn is_some(&self) -> bool {
        self.value.is_some()
    }

    /// Whether no value is present.
    #[must_use]
    pub fn is_none(&self) -> bool {
        self.value.is_none()
    }

    /// The cursor at the contained value, if there is one. Decodes nothing.
    pub(crate) fn cursor(&self) -> Option<Cursor<'a>> {
        self.value
    }

    /// The contained value, if there is one.
    ///
    /// # Errors
    ///
    /// The same as [`ContainerView::get`], for the one item this holds.
    pub fn get(&self) -> Result<Option<ValueView<'a>>, Error> {
        match self.value {
            Some(mut value) => ValueView::read(&mut value, self.item_kind).map(Some),
            None => Ok(None),
        }
    }
}

impl fmt::Debug for OptionalView<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OptionalView")
            .field("item_kind", &self.item_kind)
            .field("is_some", &self.is_some())
            .finish()
    }
}

/// A [`Kind::Struct`] or [`Kind::Embedded`], viewed in place.
///
/// A pointer with a class hash of `0` is null: it has no size field and no body, so
/// [`StructView::property_count`] is `0` and the iterator is empty.
pub struct StructView<'a> {
    class_hash: BinHash,
    property_count: u16,
    /// Positioned at the first property.
    properties: Cursor<'a>,
}

impl<'a> StructView<'a> {
    fn read(cur: &mut Cursor<'a>) -> Result<Self, Error> {
        let class_hash = cur.bin_hash()?;
        if *class_hash == 0 {
            return Ok(Self {
                class_hash,
                property_count: 0,
                properties: Cursor::new(&[], cur.numbering()),
            });
        }

        let size = cur.u32()? as usize;
        let mut properties = cur.sub(size)?;
        let property_count = properties.u16()?;

        Ok(Self {
            class_hash,
            property_count,
            properties,
        })
    }

    /// A view over `count` properties at `properties`, carrying `class_hash`. An object's
    /// root as a struct.
    pub(crate) fn from_parts(class_hash: BinHash, count: u16, properties: Cursor<'a>) -> Self {
        Self {
            class_hash,
            property_count: count,
            properties,
        }
    }

    /// The class this is an instance of, or `0` for a null pointer.
    #[must_use]
    pub fn class_hash(&self) -> BinHash {
        self.class_hash
    }

    /// How many properties it declares.
    #[must_use]
    pub fn property_count(&self) -> u16 {
        self.property_count
    }

    /// The properties, in file order.
    pub fn properties(&self) -> Properties<'a> {
        Properties::new(self.properties, self.property_count)
    }

    /// The property with the given name hash — an in-memory walk, no index needed.
    ///
    /// # Errors
    ///
    /// Whatever [`StructView::properties`] raises before it reaches the property.
    pub fn property(
        &self,
        name_hash: impl Into<BinHash>,
    ) -> Result<Option<PropertyView<'a>>, Error> {
        find_property(self.properties(), name_hash.into())
    }
}

impl fmt::Debug for StructView<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StructView")
            .field("class_hash", &self.class_hash)
            .field("property_count", &self.property_count)
            .finish()
    }
}

copy_views!(ValueView, ContainerView, MapView, OptionalView, StructView,);