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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
//! Walking a [`PropertyPath`] through a value tree, and the type rule that governs a patch.

use std::fmt;

use indexmap::IndexMap;
use ltk_hash::{BinHash, Hash as _, HashValue, HashWidth, WadHash};

use crate::{
    path::{KeyLiteral, MapKey, PropertyPath, Segment, Subscript, ValuePath, ValueSegment},
    property::{values, Kind},
    walk::{self, Declaration, TreeValue as _},
    Bin, BinObject, PropertyValueEnum, ValueSlot,
};

/// What the patch type rule compares: the kind, a container's item and key kinds, and the class
/// of an embed.
///
/// The client compares a record's kind byte against the property's registered type, and then, in
/// the reader the record shares with an ordinary property, the element tags of a container, both
/// tags of a map, and the exact class of an embed. A pointer is the exception: the client accepts
/// any class that derives from the declared one. Deciding that needs the class hierarchy, which
/// only the game has, so a pointer's class is left out of the comparison entirely and this crate
/// accepts a pointer the client might still reject.
///
/// # Examples
///
/// ```
/// use ltk_meta::{path::ValueShape, property::values, PropertyValueEnum};
///
/// let anchor: PropertyValueEnum = values::Vector2::default().into();
/// let normal: PropertyValueEnum = values::Vector3::default().into();
///
/// assert_eq!(ValueShape::of(&anchor).to_string(), "Vector2");
/// assert!(ValueShape::of(&anchor).matches(&ValueShape::of(&anchor)));
/// assert!(!ValueShape::of(&anchor).matches(&ValueShape::of(&normal)));
///
/// // A container also compares by what it holds.
/// let links: PropertyValueEnum = values::Container::from(vec![values::ObjectLink::default()]).into();
/// assert_eq!(ValueShape::of(&links).to_string(), "Container[ObjectLink]");
/// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ValueShape {
    /// The kind of the value.
    pub kind: Kind,
    /// For a container or an option the item kind, for a map the value kind.
    pub item_kind: Option<Kind>,
    /// For a map the key kind.
    pub key_kind: Option<Kind>,
    /// For an embed the class it is an instance of. A pointer's class is deliberately not
    /// recorded; see the type note above.
    pub class: Option<BinHash>,
}

impl ValueShape {
    /// The shape of `value`: its [`Declaration`], converted.
    #[must_use]
    pub fn of(value: &PropertyValueEnum) -> Self {
        walk::owned::declaration(value).into()
    }

    /// Whether the type rule accepts a value of shape `other` where this shape is expected.
    ///
    /// Every field is compared, so this currently agrees with `==`. It is a separate method
    /// because it names a rule rather than structural equality: an implementation that learned
    /// the class hierarchy could accept a pointer to a derived class here without changing what
    /// two shapes being equal means.
    #[must_use]
    #[inline]
    pub fn matches(&self, other: &Self) -> bool {
        self == other
    }
}

/// The part of a declaration the type rule compares. The count is left out, and so is a
/// pointer's class; an embed's class is kept.
///
/// # Examples
///
/// ```
/// use ltk_meta::{path::ValueShape, property::values, walk::TreeValue, PropertyValueEnum};
///
/// let pointer: PropertyValueEnum = values::Struct {
///     class_hash: 0xC1A5_0001u32.into(),
///     properties: Default::default(),
/// }
/// .into();
/// let declaration = (&pointer).declaration()?;
///
/// assert_eq!(declaration.class, Some(0xC1A5_0001u32.into()));
/// assert_eq!(ValueShape::from(declaration).class, None);
/// # Ok::<(), ltk_meta::Error>(())
/// ```
impl From<Declaration> for ValueShape {
    fn from(declaration: Declaration) -> Self {
        Self {
            kind: declaration.kind,
            item_kind: declaration.item_kind,
            key_kind: declaration.key_kind,
            class: declaration
                .class
                .filter(|_| declaration.kind == Kind::Embedded),
        }
    }
}

impl fmt::Display for ValueShape {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self.kind)?;
        match (self.key_kind, self.item_kind) {
            (Some(key), Some(item)) => write!(f, "[{key:?}, {item:?}]")?,
            (None, Some(item)) => write!(f, "[{item:?}]")?,
            _ => {}
        }
        match self.class {
            Some(class) => write!(f, " {class:08x}"),
            None => Ok(()),
        }
    }
}

/// Why a [`PropertyPath`] or a [`ValuePath`] does not name a value in the tree it was walked
/// through.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("{kind} (segment {segment})")]
pub struct ResolveError {
    segment: usize,
    kind: ResolveErrorKind,
}

impl ResolveError {
    pub(crate) fn new(segment: usize, kind: ResolveErrorKind) -> Self {
        Self { segment, kind }
    }

    /// Which segment could not be applied, counting from 0.
    ///
    /// A segment that cannot be applied because the value before it is a leaf is charged to the
    /// segment, not to the leaf: `Enabled.Size` where `Enabled` is a bool fails at segment 1.
    /// [`ResolveErrorKind::MissingObject`] happens before any segment and reports 0.
    #[must_use]
    #[inline]
    pub fn segment(&self) -> usize {
        self.segment
    }

    /// What went wrong.
    #[must_use]
    #[inline]
    pub fn kind(&self) -> ResolveErrorKind {
        self.kind
    }
}

/// The kinds of [`ResolveError`].
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ResolveErrorKind {
    /// The bin has no object with this path hash. Only [`Bin::resolve`] produces this.
    #[error("no object {0:08x}")]
    MissingObject(BinHash),
    /// The value being descended into has no property with this name hash.
    #[error("no property {0:08x}")]
    MissingProperty(BinHash),
    /// A pointer with a class hash of 0.
    ///
    /// The client dereferences unconditionally and does not document what a null pointee does, so
    /// stopping here is this crate's choice rather than a reproduction of the client's.
    #[error("the pointer is null")]
    NullPointer,
    /// A `.name` piece applied to something that is not a pointer or an embed.
    #[error("cannot descend into a {0:?}")]
    CannotDescend(Kind),
    /// A `[i]` applied to something that is not a list, list2 or option, or a `{k}` applied to
    /// something that is not a map.
    #[error("a {0:?} cannot be subscripted that way")]
    NotIndexable(Kind),
    /// A `[i]` past the end of a list, or anything but `[0]` on a present option.
    #[error("index {index} is out of range, the length is {len}")]
    IndexOutOfRange {
        /// The index that was asked for.
        index: u32,
        /// How many elements there were. An option counts as 0 or 1.
        len: usize,
    },
    /// A `{k}` whose literal does not convert to the map's key kind.
    #[error("the key does not convert to {0:?}")]
    InvalidKey(Kind),
    /// A `{k}` that converts but matches no entry.
    #[error("no entry has that key")]
    KeyNotFound,
    /// A [`ValuePath`] into an object, a pointer or an embed that does not start with a field.
    ///
    /// An object is reached by field only. The empty path names the object itself, which is not
    /// a value. A [`PropertyPath`] always starts with a field and never produces this.
    #[error("a path into an object starts with a field")]
    FieldExpected,
}

/// Why a patch record does not apply.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum PatchError {
    /// The path does not name a value in the object.
    #[error(transparent)]
    Resolve(#[from] ResolveError),
    /// The path names a value of a different type. Nothing was changed.
    #[error("type mismatch: the property is {expected}, the patch carries {found}")]
    TypeMismatch {
        /// The shape of the value already in the tree.
        expected: ValueShape,
        /// The shape of the value the patch carries.
        found: ValueShape,
    },
}

/// Which slot inside a value a subscript selects.
///
/// Decided on a shared borrow so the rules, and every error they can raise, are written once and
/// the two projections that follow cannot fail.
#[derive(Debug, Clone, Copy)]
enum Slot {
    /// An item of a list or a list2.
    Item(usize),
    /// The value inside an option, which is present.
    OptionValue,
    /// The value of a map entry.
    Entry(usize),
}

const MISSING: &str = "a Slot only ever names a slot that exists";

/// The properties of an object, a pointer's target or an embed: what a `.name` piece looks in.
type Properties = IndexMap<BinHash, PropertyValueEnum>;

/// Where the last segment of a path lands: the properties it is looked up in, the segment itself
/// and its position, for the error if it does not resolve.
type Landing<'a, 'p> = (&'a Properties, Segment<'p>, usize);

/// See [`Landing`].
type LandingMut<'a, 'p> = (&'a mut Properties, Segment<'p>, usize);

/// Whether the next `.name` piece can be applied to this value.
fn descend_check(value: &PropertyValueEnum) -> Result<(), ResolveErrorKind> {
    use PropertyValueEnum as V;
    match value {
        V::Struct(pointer) if *pointer.class_hash == 0 => Err(ResolveErrorKind::NullPointer),
        V::Struct(_) | V::Embedded(_) => Ok(()),
        other => Err(ResolveErrorKind::CannotDescend(other.kind())),
    }
}

/// The properties a `.name` piece looks a name up in. `None` exactly when [`descend_check`] fails.
fn properties_of(value: &PropertyValueEnum) -> Option<&Properties> {
    use PropertyValueEnum as V;
    match value {
        V::Struct(pointer) if *pointer.class_hash == 0 => None,
        V::Struct(inner) | V::Embedded(values::Embedded(inner)) => Some(&inner.properties),
        _ => None,
    }
}

/// See [`properties_of`].
fn properties_of_mut(value: &mut PropertyValueEnum) -> Option<&mut Properties> {
    use PropertyValueEnum as V;
    match value {
        V::Struct(pointer) if *pointer.class_hash == 0 => None,
        V::Struct(inner) | V::Embedded(values::Embedded(inner)) => Some(&mut inner.properties),
        _ => None,
    }
}

fn slot_for(
    value: &PropertyValueEnum,
    subscript: &Subscript<'_>,
) -> Result<Slot, ResolveErrorKind> {
    use PropertyValueEnum as V;

    match (value, subscript) {
        (V::Container(list), Subscript::Index(index))
        | (V::UnorderedContainer(values::UnorderedContainer(list)), Subscript::Index(index)) => {
            match (*index as usize) < list.len() {
                true => Ok(Slot::Item(*index as usize)),
                false => Err(ResolveErrorKind::IndexOutOfRange {
                    index: *index,
                    len: list.len(),
                }),
            }
        }
        (V::Optional(option), Subscript::Index(index)) => match (*index, option.is_some()) {
            (0, true) => Ok(Slot::OptionValue),
            _ => Err(ResolveErrorKind::IndexOutOfRange {
                index: *index,
                len: usize::from(option.is_some()),
            }),
        },
        (V::Map(map), Subscript::Key(literal)) => {
            let wanted =
                key_in(map, literal).ok_or(ResolveErrorKind::InvalidKey(map.key_kind()))?;
            map.entries()
                .iter()
                .position(|(key, _)| key_eq(key, &wanted))
                .map(Slot::Entry)
                .ok_or(ResolveErrorKind::KeyNotFound)
        }
        (value, _) => Err(ResolveErrorKind::NotIndexable(value.kind())),
    }
}

fn take(value: &PropertyValueEnum, slot: Slot) -> &PropertyValueEnum {
    use PropertyValueEnum as V;
    match (value, slot) {
        (V::Container(list), Slot::Item(index))
        | (V::UnorderedContainer(values::UnorderedContainer(list)), Slot::Item(index)) => {
            list.get(index).expect(MISSING)
        }
        (V::Optional(option), Slot::OptionValue) => option.value().expect(MISSING),
        (V::Map(map), Slot::Entry(index)) => &map.entries().get(index).expect(MISSING).1,
        _ => unreachable!("{MISSING}"),
    }
}

fn take_mut(value: &mut PropertyValueEnum, slot: Slot) -> ValueSlot<'_> {
    use PropertyValueEnum as V;
    match (value, slot) {
        (V::Container(list), Slot::Item(index))
        | (V::UnorderedContainer(values::UnorderedContainer(list)), Slot::Item(index)) => {
            list.slot(index).expect(MISSING)
        }
        (V::Optional(option), Slot::OptionValue) => option.slot().expect(MISSING),
        (V::Map(map), Slot::Entry(index)) => map.slot(index).expect(MISSING),
        _ => unreachable!("{MISSING}"),
    }
}

/// Returns the key that `literal` selects in `map`. Returns `None` if `literal` does not convert
/// to the key kind of `map`.
///
/// If the `Hash` keys of `map` are 8 bytes wide, converts a number literal to the raw value of the
/// key and returns `None` for a string literal. The file does not store the hash function of the
/// keys.
fn key_in(map: &values::Map, literal: &KeyLiteral<'_>) -> Option<PropertyValueEnum> {
    match (map.key_hash_width(), literal) {
        (Some(HashWidth::W8), KeyLiteral::Number(text)) => {
            Some(values::Hash::new(HashValue::wide(text.parse().ok()?)).into())
        }
        (Some(HashWidth::W8), _) => None,
        _ => key_as(map.key_kind(), literal),
    }
}

/// Returns the key that `literal` selects, as a value of `kind`. Returns a `Hash` key at
/// width 4.
///
/// The client parses the brace text as JSON and converts the result to the map's key type. A
/// number is written into an integer or float key, a string is taken as text for a string key and
/// hashed for a hash key. Anything else, including a number written with a fraction for an integer
/// key, has no conversion here. No shipped record uses a `{key}` subscript, so none of this is
/// attested in the wild.
fn key_as(kind: Kind, literal: &KeyLiteral<'_>) -> Option<PropertyValueEnum> {
    use KeyLiteral as L;

    Some(match (kind, literal) {
        (Kind::Bool, L::Bool(value)) => values::Bool::new(*value).into(),
        (Kind::BitBool, L::Bool(value)) => values::BitBool::new(*value).into(),
        (Kind::I8, L::Number(text)) => values::I8::new(text.parse().ok()?).into(),
        (Kind::U8, L::Number(text)) => values::U8::new(text.parse().ok()?).into(),
        (Kind::I16, L::Number(text)) => values::I16::new(text.parse().ok()?).into(),
        (Kind::U16, L::Number(text)) => values::U16::new(text.parse().ok()?).into(),
        (Kind::I32, L::Number(text)) => values::I32::new(text.parse().ok()?).into(),
        (Kind::U32, L::Number(text)) => values::U32::new(text.parse().ok()?).into(),
        (Kind::I64, L::Number(text)) => values::I64::new(text.parse().ok()?).into(),
        (Kind::U64, L::Number(text)) => values::U64::new(text.parse().ok()?).into(),
        (Kind::F32, L::Number(text)) => values::F32::new(text.parse().ok()?).into(),
        (Kind::String, L::String(text)) => values::String::new(text.to_string()).into(),
        (Kind::Hash, L::String(text)) => values::Hash::new(BinHash::hash_str(text)).into(),
        (Kind::Hash, L::Number(text)) => values::Hash::new(text.parse::<u32>().ok()?).into(),
        (Kind::WadChunkLink, L::String(text)) => {
            values::WadChunkLink::new(WadHash::hash_str(text)).into()
        }
        (Kind::WadChunkLink, L::Number(text)) => {
            values::WadChunkLink::new(text.parse::<u64>().ok()?).into()
        }
        _ => return None,
    })
}

macro_rules! match_key {
    ($key:expr, $wanted:expr, [$($variant:ident,)*]) => {
        match ($key, $wanted) {
            $((PropertyValueEnum::$variant(key), PropertyValueEnum::$variant(wanted)) => {
                key.value == wanted.value
            })*
            _ => false,
        }
    };
}

/// Whether a map key equals the value [`key_as`] produced, ignoring metadata.
fn key_eq(key: &PropertyValueEnum, wanted: &PropertyValueEnum) -> bool {
    match_key!(
        key,
        wanted,
        [
            Bool,
            BitBool,
            I8,
            U8,
            I16,
            U16,
            I32,
            U32,
            I64,
            U64,
            F32,
            String,
            Hash,
            WadChunkLink,
        ]
    )
}

/// Looks `segment` up and applies its subscript.
fn step<'a>(
    properties: &'a Properties,
    segment: &Segment<'_>,
    index: usize,
) -> Result<&'a PropertyValueEnum, ResolveError> {
    let name_hash = segment.name_hash();
    let value = properties
        .get(&name_hash)
        .ok_or_else(|| ResolveError::new(index, ResolveErrorKind::MissingProperty(name_hash)))?;

    match &segment.subscript {
        None => Ok(value),
        Some(subscript) => {
            let slot = slot_for(value, subscript).map_err(|kind| ResolveError::new(index, kind))?;
            Ok(take(value, slot))
        }
    }
}

/// See [`step`].
fn step_mut<'a>(
    properties: &'a mut Properties,
    segment: &Segment<'_>,
    index: usize,
) -> Result<ValueSlot<'a>, ResolveError> {
    let name_hash = segment.name_hash();
    let value = properties
        .get_mut(&name_hash)
        .ok_or_else(|| ResolveError::new(index, ResolveErrorKind::MissingProperty(name_hash)))?;

    match &segment.subscript {
        None => Ok(ValueSlot::free(value)),
        Some(subscript) => {
            let slot = slot_for(value, subscript).map_err(|kind| ResolveError::new(index, kind))?;
            Ok(take_mut(value, slot))
        }
    }
}

/// Walks every segment but the last, and returns the properties the last one is looked up in.
///
/// Splitting the walk here is what lets `patch` treat an absent leaf differently from an absent
/// step on the way down.
fn locate<'a, 'p>(
    properties: &'a Properties,
    path: &'p PropertyPath,
) -> Result<Landing<'a, 'p>, ResolveError> {
    let mut properties = properties;
    let mut segments = path.segments().enumerate().peekable();

    loop {
        let (index, segment) = segments
            .next()
            .expect("a PropertyPath has at least one segment");
        if segments.peek().is_none() {
            return Ok((properties, segment, index));
        }

        let value = step(properties, &segment, index)?;
        descend_check(value).map_err(|kind| ResolveError::new(index + 1, kind))?;
        properties = properties_of(value).expect("descend_check accepted this value");
    }
}

/// See [`locate`].
fn locate_mut<'a, 'p>(
    properties: &'a mut Properties,
    path: &'p PropertyPath,
) -> Result<LandingMut<'a, 'p>, ResolveError> {
    let mut properties = properties;
    let mut segments = path.segments().enumerate().peekable();

    loop {
        let (index, segment) = segments
            .next()
            .expect("a PropertyPath has at least one segment");
        if segments.peek().is_none() {
            return Ok((properties, segment, index));
        }

        let value = step_mut(properties, &segment, index)?.into_inner();
        descend_check(value).map_err(|kind| ResolveError::new(index + 1, kind))?;
        properties = properties_of_mut(value).expect("descend_check accepted this value");
    }
}

pub(crate) fn walk<'a>(
    properties: &'a Properties,
    path: &PropertyPath,
) -> Result<&'a PropertyValueEnum, ResolveError> {
    let (properties, segment, index) = locate(properties, path)?;
    step(properties, &segment, index)
}

pub(crate) fn walk_mut<'a>(
    properties: &'a mut Properties,
    path: &PropertyPath,
) -> Result<ValueSlot<'a>, ResolveError> {
    let (properties, segment, index) = locate_mut(properties, path)?;
    step_mut(properties, &segment, index)
}

pub(crate) fn patch_in(
    properties: &mut Properties,
    path: &PropertyPath,
    value: PropertyValueEnum,
) -> Result<Option<PropertyValueEnum>, PatchError> {
    let (properties, segment, index) = locate_mut(properties, path)?;
    let name_hash = segment.name_hash();

    if !properties.contains_key(&name_hash) {
        // The client has no insert: it patches a live object on which every property the class
        // declares already exists, holding whatever its constructor left there. Creating the leaf
        // is the closest a serialized tree gets, and only when the segment names it outright - a
        // subscript needs something to subscript.
        return match segment.subscript {
            None => {
                properties.insert(name_hash, value);
                Ok(None)
            }
            Some(_) => {
                Err(ResolveError::new(index, ResolveErrorKind::MissingProperty(name_hash)).into())
            }
        };
    }

    replace(step_mut(properties, &segment, index)?, value)
}

/// Replaces the value in `slot` with `value` under the type rule, and returns the value replaced.
fn replace(
    mut slot: ValueSlot<'_>,
    value: PropertyValueEnum,
) -> Result<Option<PropertyValueEnum>, PatchError> {
    let expected = ValueShape::of(slot.get());
    let found = ValueShape::of(&value);
    if !expected.matches(&found) {
        return Err(PatchError::TypeMismatch { expected, found });
    }

    Ok(Some(slot.set(value).expect(
        "the shapes match, so the kinds do and no slot can reject the value",
    )))
}

/// Whether [`patch_in`] would apply, and whether it would insert, without touching anything.
pub(crate) fn probe(
    properties: &Properties,
    path: &PropertyPath,
    found: ValueShape,
) -> Result<bool, PatchError> {
    let (properties, segment, index) = locate(properties, path)?;
    let name_hash = segment.name_hash();

    let Some(value) = properties.get(&name_hash) else {
        return match segment.subscript {
            None => Ok(true),
            Some(_) => {
                Err(ResolveError::new(index, ResolveErrorKind::MissingProperty(name_hash)).into())
            }
        };
    };

    let leaf = match &segment.subscript {
        None => value,
        Some(subscript) => {
            let slot = slot_for(value, subscript).map_err(|kind| ResolveError::new(index, kind))?;
            take(value, slot)
        }
    };

    let expected = ValueShape::of(leaf);
    match expected.matches(&found) {
        true => Ok(false),
        false => Err(PatchError::TypeMismatch { expected, found }),
    }
}

impl BinObject {
    /// The value at `path` inside this object.
    ///
    /// # Errors
    ///
    /// [`ResolveError`] naming the segment that could not be applied.
    ///
    /// # Examples
    ///
    /// ```
    /// use ltk_meta::{
    ///     path::PropertyPath,
    ///     property::values,
    ///     BinObject,
    /// };
    ///
    /// let path = PropertyPath::new("Elements[1]")?;
    /// // A name selects a property by the hash of its lowercased text.
    /// let elements = path.segments().next().unwrap().name_hash();
    ///
    /// let object = BinObject::builder(0x1234, 0x5678)
    ///     .property(
    ///         elements,
    ///         values::Container::from(vec![values::I32::new(10), values::I32::new(20)]),
    ///     )
    ///     .build();
    ///
    /// assert_eq!(object.resolve(&path)?, &values::I32::new(20).into());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn resolve(&self, path: &PropertyPath) -> Result<&PropertyValueEnum, ResolveError> {
        walk(&self.properties, path)
    }

    /// A mutable handle on the value at `path` inside this object.
    ///
    /// This is the unchecked way in: it hands back whatever is there and applies no type rule.
    /// [`BinObject::patch`] is the one that reproduces the client.
    ///
    /// # Errors
    ///
    /// The same as [`BinObject::resolve`].
    pub fn resolve_mut(&mut self, path: &PropertyPath) -> Result<ValueSlot<'_>, ResolveError> {
        walk_mut(&mut self.properties, path)
    }

    /// Sets the property at `path` the way a `PTCH` record does.
    ///
    /// Returns the value that was replaced, or `None` when the leaf did not exist and was
    /// created. Creating the leaf is what makes 2,455 of Riot's shipped records apply: the client
    /// patches a live object on which every property its class declares already exists, so there
    /// the property is never absent. A leaf named by a subscript is never created, and neither is
    /// a step on the way down: an absent intermediate is a [`ResolveErrorKind::MissingProperty`],
    /// where the client would patch into the default the constructor left behind.
    ///
    /// # Errors
    ///
    /// [`PatchError::Resolve`] if `path` does not name a property, or
    /// [`PatchError::TypeMismatch`] if it names one of a different shape, in which case nothing
    /// is changed.
    pub fn patch(
        &mut self,
        path: &PropertyPath,
        value: PropertyValueEnum,
    ) -> Result<Option<PropertyValueEnum>, PatchError> {
        patch_in(&mut self.properties, path, value)
    }

    /// Whether [`BinObject::patch`] would apply, and whether it would create the leaf.
    pub(crate) fn probe(
        &self,
        path: &PropertyPath,
        value: &PropertyValueEnum,
    ) -> Result<bool, PatchError> {
        probe(&self.properties, path, ValueShape::of(value))
    }
}

impl values::Struct {
    /// The value at `path` inside this pointer's target.
    ///
    /// # Errors
    ///
    /// [`ResolveErrorKind::NullPointer`] at segment 0 if the class hash is 0, otherwise the same
    /// as [`BinObject::resolve`].
    pub fn resolve(&self, path: &PropertyPath) -> Result<&PropertyValueEnum, ResolveError> {
        self.null_check()?;
        walk(&self.properties, path)
    }

    /// See [`values::Struct::resolve`] and [`BinObject::resolve_mut`].
    ///
    /// # Errors
    ///
    /// The same as [`values::Struct::resolve`].
    pub fn resolve_mut(&mut self, path: &PropertyPath) -> Result<ValueSlot<'_>, ResolveError> {
        self.null_check()?;
        walk_mut(&mut self.properties, path)
    }

    /// See [`BinObject::patch`].
    ///
    /// # Errors
    ///
    /// The same as [`BinObject::patch`], plus [`ResolveErrorKind::NullPointer`].
    pub fn patch(
        &mut self,
        path: &PropertyPath,
        value: PropertyValueEnum,
    ) -> Result<Option<PropertyValueEnum>, PatchError> {
        self.null_check()?;
        patch_in(&mut self.properties, path, value)
    }

    fn null_check(&self) -> Result<(), ResolveError> {
        match *self.class_hash {
            0 => Err(ResolveError::new(0, ResolveErrorKind::NullPointer)),
            _ => Ok(()),
        }
    }
}

impl values::Embedded {
    /// The value at `path` inside this embed. See [`BinObject::resolve`].
    ///
    /// # Errors
    ///
    /// The same as [`BinObject::resolve`]. An embed is inline, so unlike a pointer it is never
    /// null and a class hash of 0 is not special here.
    pub fn resolve(&self, path: &PropertyPath) -> Result<&PropertyValueEnum, ResolveError> {
        walk(&self.0.properties, path)
    }

    /// See [`BinObject::resolve_mut`].
    ///
    /// # Errors
    ///
    /// The same as [`values::Embedded::resolve`].
    pub fn resolve_mut(&mut self, path: &PropertyPath) -> Result<ValueSlot<'_>, ResolveError> {
        walk_mut(&mut self.0.properties, path)
    }

    /// See [`BinObject::patch`].
    ///
    /// # Errors
    ///
    /// The same as [`BinObject::patch`].
    pub fn patch(
        &mut self,
        path: &PropertyPath,
        value: PropertyValueEnum,
    ) -> Result<Option<PropertyValueEnum>, PatchError> {
        patch_in(&mut self.0.properties, path, value)
    }
}

impl PropertyValueEnum {
    /// The value at `path` relative to this one.
    ///
    /// The first segment applies to this value, so it has to be a pointer or an embed for a path
    /// to go anywhere at all.
    ///
    /// # Errors
    ///
    /// [`ResolveErrorKind::CannotDescend`] or [`ResolveErrorKind::NullPointer`] at segment 0 if
    /// this value cannot be descended into, otherwise the same as [`BinObject::resolve`].
    pub fn resolve(&self, path: &PropertyPath) -> Result<&PropertyValueEnum, ResolveError> {
        descend_check(self).map_err(|kind| ResolveError::new(0, kind))?;
        walk(
            properties_of(self).expect("descend_check accepted this value"),
            path,
        )
    }

    /// See [`PropertyValueEnum::resolve`] and [`BinObject::resolve_mut`].
    ///
    /// # Errors
    ///
    /// The same as [`PropertyValueEnum::resolve`].
    pub fn resolve_mut(&mut self, path: &PropertyPath) -> Result<ValueSlot<'_>, ResolveError> {
        descend_check(self).map_err(|kind| ResolveError::new(0, kind))?;
        walk_mut(
            properties_of_mut(self).expect("descend_check accepted this value"),
            path,
        )
    }
}

impl Bin {
    /// The value at `path` inside object `object_hash`.
    ///
    /// # Errors
    ///
    /// [`ResolveErrorKind::MissingObject`] if the bin has no such object, otherwise the same as
    /// [`BinObject::resolve`].
    pub fn resolve(
        &self,
        object_hash: impl Into<BinHash>,
        path: &PropertyPath,
    ) -> Result<&PropertyValueEnum, ResolveError> {
        self.object(object_hash)?.resolve(path)
    }

    /// See [`Bin::resolve`] and [`BinObject::resolve_mut`].
    ///
    /// # Errors
    ///
    /// The same as [`Bin::resolve`].
    pub fn resolve_mut(
        &mut self,
        object_hash: impl Into<BinHash>,
        path: &PropertyPath,
    ) -> Result<ValueSlot<'_>, ResolveError> {
        let object_hash = object_hash.into();
        self.objects
            .get_mut(&object_hash)
            .ok_or_else(|| ResolveError::new(0, ResolveErrorKind::MissingObject(object_hash)))?
            .resolve_mut(path)
    }

    /// Sets a property inside object `object_hash` the way a `PTCH` record does.
    ///
    /// See [`BinObject::patch`].
    ///
    /// # Errors
    ///
    /// The same as [`BinObject::patch`], plus [`ResolveErrorKind::MissingObject`].
    pub fn patch(
        &mut self,
        object_hash: impl Into<BinHash>,
        path: &PropertyPath,
        value: PropertyValueEnum,
    ) -> Result<Option<PropertyValueEnum>, PatchError> {
        let object_hash = object_hash.into();
        let object = self
            .objects
            .get_mut(&object_hash)
            .ok_or_else(|| ResolveError::new(0, ResolveErrorKind::MissingObject(object_hash)))?;

        object.patch(path, value)
    }

    fn object(&self, object_hash: impl Into<BinHash>) -> Result<&BinObject, ResolveError> {
        let object_hash = object_hash.into();
        self.objects
            .get(&object_hash)
            .ok_or_else(|| ResolveError::new(0, ResolveErrorKind::MissingObject(object_hash)))
    }
}

impl MapKey {
    /// The key a `{key}` literal selects in a map keyed by `kind`, or `None` when the literal
    /// does not convert.
    ///
    /// The conversion is the one [`BinObject::resolve`] applies to a `{key}` subscript: a
    /// number fills an integer or float key, a string is the text of a string key and is hashed
    /// for a `Hash` or `WadChunkLink` key, and a number is the raw value of a hashed key.
    ///
    /// # Examples
    ///
    /// ```
    /// use ltk_hash::{BinHash, Hash as _};
    /// use ltk_meta::{
    ///     path::{KeyLiteral, MapKey},
    ///     property::Kind,
    /// };
    ///
    /// let weapon = KeyLiteral::from("weapon");
    /// assert_eq!(
    ///     MapKey::from_literal(&weapon, Kind::Hash),
    ///     Some(MapKey::Hash(BinHash::hash_str("weapon").into()))
    /// );
    /// assert_eq!(MapKey::from_literal(&weapon, Kind::U32), None);
    /// ```
    #[must_use]
    pub fn from_literal(literal: &KeyLiteral<'_>, kind: Kind) -> Option<Self> {
        (&key_as(kind, literal)?).map_key().ok()
    }
}

/// Where a [`ValuePath`] stands between two of its segments.
enum Cursor<'a> {
    /// The properties of an object, a pointer's target or an embed, before any segment.
    Properties(&'a Properties),
    /// The value the segments so far reached.
    Value(&'a PropertyValueEnum),
}

/// See [`Cursor`].
enum CursorMut<'a> {
    Properties(&'a mut Properties),
    Value(ValueSlot<'a>),
}

/// The property `field` of `properties`.
fn field_of(
    properties: &Properties,
    field: BinHash,
) -> Result<&PropertyValueEnum, ResolveErrorKind> {
    properties
        .get(&field)
        .ok_or(ResolveErrorKind::MissingProperty(field))
}

/// Which slot an [`ValueSegment::Index`] or a [`ValueSegment::Key`] selects inside `value`.
///
/// The rules of [`slot_for`], with the key already of a kind: a key of another kind than the
/// map's is [`ResolveErrorKind::InvalidKey`]. An index past `u32::MAX` is out of range of every
/// list and reports `u32::MAX`.
fn slot_at(value: &PropertyValueEnum, segment: &ValueSegment) -> Result<Slot, ResolveErrorKind> {
    use PropertyValueEnum as V;

    let out_of_range = |index: usize, len: usize| ResolveErrorKind::IndexOutOfRange {
        index: u32::try_from(index).unwrap_or(u32::MAX),
        len,
    };
    match (value, segment) {
        (V::Container(list), ValueSegment::Index(index))
        | (V::UnorderedContainer(values::UnorderedContainer(list)), ValueSegment::Index(index)) => {
            match *index < list.len() {
                true => Ok(Slot::Item(*index)),
                false => Err(out_of_range(*index, list.len())),
            }
        }
        (V::Optional(option), ValueSegment::Index(index)) => match (*index, option.is_some()) {
            (0, true) => Ok(Slot::OptionValue),
            _ => Err(out_of_range(*index, usize::from(option.is_some()))),
        },
        (V::Map(map), ValueSegment::Key(key)) => {
            if key.kind() != map.key_kind() {
                return Err(ResolveErrorKind::InvalidKey(map.key_kind()));
            }
            map.entries()
                .iter()
                .position(|(entry, _)| entry.map_key().is_ok_and(|entry| entry == *key))
                .map(Slot::Entry)
                .ok_or(ResolveErrorKind::KeyNotFound)
        }
        (value, _) => Err(ResolveErrorKind::NotIndexable(value.kind())),
    }
}

/// Applies `segments` from `cursor`, and returns where they stop.
///
/// A field descends into an object, a pointer or an embed; an index or a key subscripts the value
/// reached. The traversal rules are [`PropertyPath`]'s. An error names the position of the
/// segment in `segments` plus `offset`.
fn walk_at<'a>(
    mut cursor: Cursor<'a>,
    segments: &[ValueSegment],
    offset: usize,
) -> Result<Cursor<'a>, ResolveError> {
    for (index, segment) in segments.iter().enumerate() {
        let error = |kind| ResolveError::new(offset + index, kind);
        let value = match (cursor, segment) {
            (Cursor::Properties(properties), ValueSegment::Field(field)) => {
                field_of(properties, *field).map_err(error)?
            }
            (Cursor::Value(value), ValueSegment::Field(field)) => {
                descend_check(value).map_err(error)?;
                let properties = properties_of(value).expect("descend_check accepted this value");
                field_of(properties, *field).map_err(error)?
            }
            (Cursor::Properties(_), _) => return Err(error(ResolveErrorKind::FieldExpected)),
            (Cursor::Value(value), subscript) => {
                take(value, slot_at(value, subscript).map_err(error)?)
            }
        };
        cursor = Cursor::Value(value);
    }
    Ok(cursor)
}

/// See [`walk_at`].
fn walk_at_mut<'a>(
    mut cursor: CursorMut<'a>,
    segments: &[ValueSegment],
    offset: usize,
) -> Result<CursorMut<'a>, ResolveError> {
    for (index, segment) in segments.iter().enumerate() {
        let error = |kind| ResolveError::new(offset + index, kind);
        let slot = match (cursor, segment) {
            (CursorMut::Properties(properties), ValueSegment::Field(field)) => ValueSlot::free(
                properties
                    .get_mut(field)
                    .ok_or_else(|| error(ResolveErrorKind::MissingProperty(*field)))?,
            ),
            (CursorMut::Value(slot), ValueSegment::Field(field)) => {
                let value = slot.into_inner();
                descend_check(value).map_err(error)?;
                let properties =
                    properties_of_mut(value).expect("descend_check accepted this value");
                ValueSlot::free(
                    properties
                        .get_mut(field)
                        .ok_or_else(|| error(ResolveErrorKind::MissingProperty(*field)))?,
                )
            }
            (CursorMut::Properties(_), _) => return Err(error(ResolveErrorKind::FieldExpected)),
            (CursorMut::Value(slot), subscript) => {
                let value = slot.into_inner();
                let at = slot_at(value, subscript).map_err(error)?;
                take_mut(value, at)
            }
        };
        cursor = CursorMut::Value(slot);
    }
    Ok(cursor)
}

/// The value `path` names inside `properties`.
fn resolve_in<'a>(
    properties: &'a Properties,
    path: &ValuePath,
) -> Result<&'a PropertyValueEnum, ResolveError> {
    match walk_at(Cursor::Properties(properties), path.segments(), 0)? {
        Cursor::Value(value) => Ok(value),
        Cursor::Properties(_) => Err(ResolveError::new(0, ResolveErrorKind::FieldExpected)),
    }
}

/// See [`resolve_in`].
fn resolve_in_mut<'a>(
    properties: &'a mut Properties,
    path: &ValuePath,
) -> Result<ValueSlot<'a>, ResolveError> {
    match walk_at_mut(CursorMut::Properties(properties), path.segments(), 0)? {
        CursorMut::Value(slot) => Ok(slot),
        CursorMut::Properties(_) => Err(ResolveError::new(0, ResolveErrorKind::FieldExpected)),
    }
}

/// [`patch_in`] by a [`ValuePath`].
fn patch_at_in(
    properties: &mut Properties,
    path: &ValuePath,
    value: PropertyValueEnum,
) -> Result<Option<PropertyValueEnum>, PatchError> {
    let segments = path.segments();
    let Some((ValueSegment::Field(field), parents)) = segments.split_last() else {
        return replace(resolve_in_mut(properties, path)?, value);
    };

    let properties = match walk_at_mut(CursorMut::Properties(properties), parents, 0)? {
        CursorMut::Properties(properties) => properties,
        CursorMut::Value(slot) => {
            let value = slot.into_inner();
            descend_check(value).map_err(|kind| ResolveError::new(parents.len(), kind))?;
            properties_of_mut(value).expect("descend_check accepted this value")
        }
    };
    match properties.get_mut(field) {
        // The leaf the path names outright is created, as `patch_in` creates it.
        None => {
            properties.insert(*field, value);
            Ok(None)
        }
        Some(existing) => replace(ValueSlot::free(existing), value),
    }
}

impl BinObject {
    /// The value at `path` inside this object.
    ///
    /// The traversal rules are [`BinObject::resolve`]'s. A field segment names a property by its
    /// hash, and a key segment selects a map entry by an equal key of the map's key kind. An
    /// error names a segment of `path`.
    ///
    /// # Errors
    ///
    /// [`ResolveError`] naming the segment that could not be applied.
    /// [`ResolveErrorKind::FieldExpected`] for the empty path and for a path that starts with a
    /// subscript.
    ///
    /// # Examples
    ///
    /// ```
    /// use ltk_hash::BinHash;
    /// use ltk_meta::{
    ///     path::{ValuePath, ValueSegment},
    ///     property::values,
    ///     BinObject,
    /// };
    ///
    /// // A field whose plaintext name is unknown.
    /// let elements = BinHash(0x1e6b_a0c4);
    /// let object = BinObject::builder(0x1234, 0x5678)
    ///     .property(
    ///         elements,
    ///         values::Container::from(vec![values::I32::new(10), values::I32::new(20)]),
    ///     )
    ///     .build();
    ///
    /// let path: ValuePath = [ValueSegment::Field(elements), ValueSegment::Index(1)]
    ///     .into_iter()
    ///     .collect();
    /// assert_eq!(object.resolve_at(&path)?, &values::I32::new(20).into());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn resolve_at(&self, path: &ValuePath) -> Result<&PropertyValueEnum, ResolveError> {
        resolve_in(&self.properties, path)
    }

    /// A mutable handle on the value at `path` inside this object. See
    /// [`BinObject::resolve_mut`] and [`BinObject::resolve_at`].
    ///
    /// # Errors
    ///
    /// The same as [`BinObject::resolve_at`].
    pub fn resolve_at_mut(&mut self, path: &ValuePath) -> Result<ValueSlot<'_>, ResolveError> {
        resolve_in_mut(&mut self.properties, path)
    }

    /// Sets the property at `path` the way [`BinObject::patch`] sets it.
    ///
    /// The type rule and the creation of an absent leaf are [`BinObject::patch`]'s. A leaf
    /// named by a field segment is created; a leaf named by a subscript never is.
    ///
    /// # Errors
    ///
    /// [`PatchError::Resolve`] if `path` does not name a property, with the kinds of
    /// [`BinObject::resolve_at`], or [`PatchError::TypeMismatch`] if it names one of a different
    /// shape, in which case nothing is changed.
    pub fn patch_at(
        &mut self,
        path: &ValuePath,
        value: PropertyValueEnum,
    ) -> Result<Option<PropertyValueEnum>, PatchError> {
        patch_at_in(&mut self.properties, path, value)
    }
}

impl values::Struct {
    /// See [`BinObject::resolve_at`].
    ///
    /// # Errors
    ///
    /// [`ResolveErrorKind::NullPointer`] at segment 0 if the class hash is 0, otherwise the same
    /// as [`BinObject::resolve_at`].
    pub fn resolve_at(&self, path: &ValuePath) -> Result<&PropertyValueEnum, ResolveError> {
        self.null_check()?;
        resolve_in(&self.properties, path)
    }

    /// See [`BinObject::resolve_at_mut`].
    ///
    /// # Errors
    ///
    /// The same as [`values::Struct::resolve_at`].
    pub fn resolve_at_mut(&mut self, path: &ValuePath) -> Result<ValueSlot<'_>, ResolveError> {
        self.null_check()?;
        resolve_in_mut(&mut self.properties, path)
    }

    /// See [`BinObject::patch_at`].
    ///
    /// # Errors
    ///
    /// The same as [`BinObject::patch_at`], plus [`ResolveErrorKind::NullPointer`].
    pub fn patch_at(
        &mut self,
        path: &ValuePath,
        value: PropertyValueEnum,
    ) -> Result<Option<PropertyValueEnum>, PatchError> {
        self.null_check()?;
        patch_at_in(&mut self.properties, path, value)
    }
}

impl values::Embedded {
    /// See [`BinObject::resolve_at`].
    ///
    /// # Errors
    ///
    /// The same as [`BinObject::resolve_at`].
    pub fn resolve_at(&self, path: &ValuePath) -> Result<&PropertyValueEnum, ResolveError> {
        resolve_in(&self.0.properties, path)
    }

    /// See [`BinObject::resolve_at_mut`].
    ///
    /// # Errors
    ///
    /// The same as [`BinObject::resolve_at`].
    pub fn resolve_at_mut(&mut self, path: &ValuePath) -> Result<ValueSlot<'_>, ResolveError> {
        resolve_in_mut(&mut self.0.properties, path)
    }

    /// See [`BinObject::patch_at`].
    ///
    /// # Errors
    ///
    /// The same as [`BinObject::patch_at`].
    pub fn patch_at(
        &mut self,
        path: &ValuePath,
        value: PropertyValueEnum,
    ) -> Result<Option<PropertyValueEnum>, PatchError> {
        patch_at_in(&mut self.0.properties, path, value)
    }
}

impl PropertyValueEnum {
    /// The value at `path` relative to this one.
    ///
    /// The first segment applies to this value: a field descends into a pointer or an embed, an
    /// index or a key subscripts a list, an option or a map. The empty path names this value.
    ///
    /// # Errors
    ///
    /// The kinds of [`BinObject::resolve_at`], [`ResolveErrorKind::FieldExpected`] excepted.
    pub fn resolve_at(&self, path: &ValuePath) -> Result<&PropertyValueEnum, ResolveError> {
        match walk_at(Cursor::Value(self), path.segments(), 0)? {
            Cursor::Value(value) => Ok(value),
            Cursor::Properties(_) => unreachable!("a walk from a value never returns properties"),
        }
    }

    /// See [`PropertyValueEnum::resolve_at`] and [`BinObject::resolve_at_mut`].
    ///
    /// # Errors
    ///
    /// The same as [`PropertyValueEnum::resolve_at`].
    pub fn resolve_at_mut(&mut self, path: &ValuePath) -> Result<ValueSlot<'_>, ResolveError> {
        match walk_at_mut(CursorMut::Value(ValueSlot::free(self)), path.segments(), 0)? {
            CursorMut::Value(slot) => Ok(slot),
            CursorMut::Properties(_) => {
                unreachable!("a walk from a value never returns properties")
            }
        }
    }
}

impl Bin {
    /// The value at `path` inside object `object_hash`. See [`BinObject::resolve_at`].
    ///
    /// # Errors
    ///
    /// [`ResolveErrorKind::MissingObject`] if the bin has no such object, otherwise the same as
    /// [`BinObject::resolve_at`].
    pub fn resolve_at(
        &self,
        object_hash: impl Into<BinHash>,
        path: &ValuePath,
    ) -> Result<&PropertyValueEnum, ResolveError> {
        self.object(object_hash)?.resolve_at(path)
    }

    /// See [`Bin::resolve_at`] and [`BinObject::resolve_at_mut`].
    ///
    /// # Errors
    ///
    /// The same as [`Bin::resolve_at`].
    pub fn resolve_at_mut(
        &mut self,
        object_hash: impl Into<BinHash>,
        path: &ValuePath,
    ) -> Result<ValueSlot<'_>, ResolveError> {
        self.object_mut(object_hash)?.resolve_at_mut(path)
    }

    /// Sets a property inside object `object_hash`. See [`BinObject::patch_at`].
    ///
    /// # Errors
    ///
    /// The same as [`BinObject::patch_at`], plus [`ResolveErrorKind::MissingObject`].
    pub fn patch_at(
        &mut self,
        object_hash: impl Into<BinHash>,
        path: &ValuePath,
        value: PropertyValueEnum,
    ) -> Result<Option<PropertyValueEnum>, PatchError> {
        self.object_mut(object_hash)?.patch_at(path, value)
    }

    fn object_mut(
        &mut self,
        object_hash: impl Into<BinHash>,
    ) -> Result<&mut BinObject, ResolveError> {
        let object_hash = object_hash.into();
        self.objects
            .get_mut(&object_hash)
            .ok_or_else(|| ResolveError::new(0, ResolveErrorKind::MissingObject(object_hash)))
    }
}