havok_serde/de/mod.rs
1// SPDX-License-Identifier: Apache-2.0 OR MIT
2//
3// The following code was written by modifying serde ver. 1.0.202.
4// See: https://github.com/serde-rs/serde/commit/58b3af4c2915c3ae789778a11f3b7a468c1cec17
5//
6// And serde holds the same license as Rust. https://github.com/rust-lang/rust/pull/43498
7//
8// The default implementation does not fully express Havok's special XML format.
9//
10// # Modification details
11// - Rust std types -> Havok Types
12// - Changed serde method to Havok XML& binary data signatures, which are easier to modify.
13//! Deserialization
14
15mod impls;
16mod seed;
17mod size_hint;
18
19use havok_types::{
20 CString, Matrix3, Matrix4, Pointer, QsTransform, Quaternion, Rotation, StringPtr, Transform,
21 Ulong, Variant, Vector4, f16,
22};
23
24use crate::lib::*;
25
26#[cfg(feature = "std")]
27#[doc(no_inline)]
28pub use std::error::Error as StdError;
29
30////////////////////////////////////////////////////////////////////////////////
31
32macro_rules! declare_error_trait {
33 (Error: Sized $(+ $($supertrait:ident)::+)*) => {
34 /// The `Error` trait allows `Deserialize` implementations to create descriptive
35 /// error messages belonging to the `Deserializer` against which they are
36 /// currently running.
37 ///
38 /// Every `Deserializer` declares an `Error` type that encompasses both
39 /// general-purpose deserialization errors as well as errors specific to the
40 /// particular deserialization format. For example the `Error` type of
41 /// `serde_json` can represent errors like an invalid JSON escape sequence or an
42 /// unterminated string literal, in addition to the error cases that are part of
43 /// this trait.
44 ///
45 /// Most deserializers should only need to provide the `Error::custom` method
46 /// and inherit the default behavior for the other methods.
47 ///
48 /// # Example implementation
49 ///
50 /// The [example data format] presented on the website shows an error
51 /// type appropriate for a basic JSON data format.
52 ///
53 /// [example data format]: https://serde.rs/data-format.html
54 pub trait Error: Sized $(+ $($supertrait)::+)* {
55 /// Raised when there is general error when deserializing a type.
56 ///
57 /// The message should not be capitalized and should not end with a period.
58 fn custom<T>(msg: T) -> Self
59 where
60 T: Display;
61
62 /// Raised when a `Deserialize` receives a type different from what it was
63 /// expecting.
64 ///
65 /// The `unexp` argument provides information about what type was received.
66 /// This is the type that was present in the input file or other source data
67 /// of the Deserializer.
68 ///
69 /// The `exp` argument provides information about what type was being
70 /// expected. This is the type that is written in the program.
71 ///
72 /// For example if we try to deserialize a String out of a JSON file
73 /// containing an integer, the unexpected type is the integer and the
74 /// expected type is the string.
75 #[cold]
76 fn invalid_type(unexp: Unexpected, exp: &dyn Expected) -> Self {
77 Error::custom(format_args!("invalid type: {}, expected {}", unexp, exp))
78 }
79
80 /// Raised when a `Deserialize` receives a value of the right type but that
81 /// is wrong for some other reason.
82 ///
83 /// The `unexp` argument provides information about what value was received.
84 /// This is the value that was present in the input file or other source
85 /// data of the Deserializer.
86 ///
87 /// The `exp` argument provides information about what value was being
88 /// expected. This is the type that is written in the program.
89 ///
90 /// For example if we try to deserialize a String out of some binary data
91 /// that is not valid UTF-8, the unexpected value is the bytes and the
92 /// expected value is a string.
93 #[cold]
94 fn invalid_value(unexp: Unexpected, exp: &dyn Expected) -> Self {
95 Error::custom(format_args!("invalid value: {}, expected {}", unexp, exp))
96 }
97
98 /// Raised when deserializing a sequence or map and the input data contains
99 /// too many or too few elements.
100 ///
101 /// The `len` argument is the number of elements encountered. The sequence
102 /// or map may have expected more arguments or fewer arguments.
103 ///
104 /// The `exp` argument provides information about what data was being
105 /// expected. For example `exp` might say that a tuple of size 6 was
106 /// expected.
107 #[cold]
108 fn invalid_length(len: usize, exp: &dyn Expected) -> Self {
109 Error::custom(format_args!("invalid length {}, expected {}", len, exp))
110 }
111
112 /// Raised when a `Deserialize` enum type received a variant with an
113 /// unrecognized name.
114 #[cold]
115 fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self {
116 if expected.is_empty() {
117 Error::custom(format_args!(
118 "unknown variant `{}`, there are no variants",
119 variant
120 ))
121 } else {
122 Error::custom(format_args!(
123 "unknown variant `{}`, expected {}",
124 variant,
125 OneOf { names: expected }
126 ))
127 }
128 }
129
130 /// Raised when a `Deserialize` struct type received a field with an
131 /// unrecognized name.
132 #[cold]
133 fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self {
134 if expected.is_empty() {
135 Error::custom(format_args!(
136 "unknown field `{}`, there are no fields",
137 field
138 ))
139 } else {
140 Error::custom(format_args!(
141 "unknown field `{}`, expected {}",
142 field,
143 OneOf { names: expected }
144 ))
145 }
146 }
147
148 /// Raised when a `Deserialize` struct type expected to receive a required
149 /// field with a particular name but that field was not present in the
150 /// input.
151 #[cold]
152 fn missing_field(field: &'static str) -> Self {
153 Error::custom(format_args!("missing field `{}`", field))
154 }
155
156 /// Raised when a `Deserialize` struct type received more than one of the
157 /// same field.
158 #[cold]
159 fn duplicate_field(field: &'static str) -> Self {
160 Error::custom(format_args!("duplicate field `{}`", field))
161 }
162 }
163 }
164}
165
166#[cfg(feature = "std")]
167declare_error_trait!(Error: Sized + StdError);
168
169#[cfg(not(feature = "std"))]
170declare_error_trait!(Error: Sized + Debug + Display);
171
172/// `Unexpected` represents an unexpected invocation of any one of the `Visitor`
173/// trait methods.
174///
175/// This is used as an argument to the `invalid_type`, `invalid_value`, and
176/// `invalid_length` methods of the `Error` trait to build error messages.
177#[derive(Clone, PartialEq, Debug)]
178pub enum Unexpected<'a> {
179 /// No type information.
180 ///
181 /// - C++ type: `void`
182 ///
183 /// # Examples
184 ///
185 /// This is often used to fill in generics elements with types for which generics are not used.
186 /// - `hkArray<hkBool>` -> `vtype`: `TYPE_ARRAY`, `vsubtype`: `TYPE_BOOL`
187 /// - `hkBool` -> `vtype`: `TYPE_BOOL`, `vsubtype`: `TYPE_VOID`
188 /// - There is also a pattern `hkArray<void>`. The type information is unknown, but this member always contains the `SERIALIZE_IGNORED` flag and can be skipped.
189 Void,
190
191 /// - C++ type: `hkBool` (`bool`)
192 Bool(bool),
193
194 /// - C++ type: `hkChar` (`signed char`)
195 Char(char),
196
197 /// - C++ type: `hkInt8` (`signed char`)
198 Int8(i8),
199
200 /// - C++ type: `hkUint8` (`unsigned char`)
201 Uint8(u8),
202
203 /// - C++ type: `hkInt16` (`signed short`)
204 Int16(i16),
205
206 /// - C++ type: `hkUint16` (`unsigned short`)
207 Uint16(u16),
208
209 /// - C++ type: `hkInt32` (`signed int`)
210 Int32(i32),
211
212 /// - C++ type: `hkUint32` (`unsigned int`)
213 Uint32(u32),
214
215 /// - C++ type: `hkInt64` (`signed long long`)
216 Int64(i64),
217
218 /// - C++ type: `hkUint64` (`unsigned long long`)
219 Uint64(u64),
220
221 /// - C++ type: `hkReal` (`float`)
222 Real(f32),
223
224 /// - C++ type: `hkVector4`
225 Vector4(Vector4),
226
227 /// - C++ type: `hkQuaternion`
228 Quaternion(Quaternion),
229
230 /// - C++ type: `hkMatrix3`
231 Matrix3(Matrix3),
232
233 /// - C++ type: `hkRotation`
234 Rotation(Rotation),
235
236 /// - C++ type: `hkQsTransform`
237 QsTransform(QsTransform),
238
239 /// - C++ type: `hkMatrix4`
240 Matrix4(Matrix4),
241
242 /// - C++ type: `hkTransform`
243 Transform(Transform),
244
245 /// - C++ type: `T*`
246 Pointer(Pointer),
247
248 /// Array of items of type T.
249 /// - C++ type: `hkArray<T>`
250 Array,
251
252 /// enum type that stores only the size of `SizeType` in memory.
253 /// - C++ type: `hkEnum<Enum,SizeType>`
254 Enum,
255
256 /// - C++ type: `class` | `struct`
257 Struct,
258
259 /// - C++ type: `hkVariant` (void* and hkClass*) type
260 Variant(Variant),
261
262 /// Null terminated string.
263 /// - C++ type: `char*`
264 CString(CString<'a>),
265
266 /// - C++ type: `hkUlong` (`unsigned long`), defined to always be the same size as a pointer
267 Ulong(Ulong),
268
269 /// - C++ type: `hkFlags<ENUM, SizeType>` - 8,16,32 bits of named values.
270 Flags,
271
272 /// - C++ type: `hkHalf` (`hkInt16`), 16-bit float value
273 Half(f16),
274
275 /// Null-terminated string type.
276 ///
277 /// There is a flag `StringFlags::OWNED_FLAG = 0x1` defined in the class, so `Owned` is also possible.
278 ///
279 /// It is unclear which segment (stack, heap, or other) is being pointed to because of the raw pointer.
280 /// - C++ type: `hkStringPtr`
281 StringPtr(StringPtr<'a>),
282
283 /// Other types
284 Other(&'a str),
285}
286
287impl fmt::Display for Unexpected<'_> {
288 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
289 use self::Unexpected::*;
290 match *self {
291 Void => write!(formatter, "void"),
292 Bool(b) => write!(formatter, "boolean `{b}`"),
293 Char(c) => write!(formatter, "character `{c}`"),
294 Int8(i) => write!(formatter, "8-bit integer `{i}`"),
295 Uint8(i) => write!(formatter, "8-bit unsigned integer `{i}`"),
296 Int16(i) => write!(formatter, "16-bit integer `{i}`"),
297 Uint16(i) => write!(formatter, "16-bit unsigned integer `{i}`"),
298 Int32(i) => write!(formatter, "32-bit integer `{i}`"),
299 Uint32(i) => write!(formatter, "32-bit unsigned integer `{i}`"),
300 Int64(i) => write!(formatter, "64-bit integer `{i}`"),
301 Uint64(i) => write!(formatter, "64-bit unsigned integer `{i}`"),
302 Real(f) => write!(formatter, "floating point `{f}`"),
303 Vector4(ref v) => write!(formatter, "vector4 `{v:?}`"),
304 Quaternion(ref q) => write!(formatter, "quaternion `{q:?}`"),
305 Matrix3(ref m) => write!(formatter, "matrix3 `{m:?}`"),
306 Rotation(ref r) => write!(formatter, "rotation `{r:?}`"),
307 QsTransform(ref t) => write!(formatter, "qs transform `{t:?}`"),
308 Matrix4(ref m) => write!(formatter, "matrix4 `{m:?}`"),
309 Transform(ref t) => write!(formatter, "transform `{t:?}`"),
310 Pointer(ref p) => write!(formatter, "pointer `{p:?}`"),
311 Array => formatter.write_str("array"),
312 Enum => formatter.write_str("enum"),
313 Struct => formatter.write_str("struct"),
314 Variant(ref v) => write!(formatter, "variant `{v:?}`"),
315 CString(ref s) => write!(formatter, "C string `{s:?}`"),
316 Ulong(u) => write!(formatter, "ulong `{u}`"),
317 Flags => formatter.write_str("flags"),
318 Half(h) => write!(formatter, "half `{h}`"),
319 StringPtr(ref s) => write!(formatter, "string pointer `{s:?}`"),
320 Other(other) => formatter.write_str(other),
321 }
322 }
323}
324
325/// `Expected` represents an explanation of what data a `Visitor` was expecting
326/// to receive.
327///
328/// This is used as an argument to the `invalid_type`, `invalid_value`, and
329/// `invalid_length` methods of the `Error` trait to build error messages. The
330/// message should be a noun or noun phrase that completes the sentence "This
331/// Visitor expects to receive ...", for example the message could be "an
332/// integer between 0 and 64". The message should not be capitalized and should
333/// not end with a period.
334///
335/// Within the context of a `Visitor` implementation, the `Visitor` itself
336/// (`&self`) is an implementation of this trait.
337///
338/// Outside of a `Visitor`, `&"..."` can be used.
339///
340/// ```edition2021
341/// # use havok_serde::de::{self, Unexpected};
342/// #
343/// # fn example<E>() -> Result<(), E>
344/// # where
345/// # E: de::Error,
346/// # {
347/// # let v = true;
348/// return Err(de::Error::invalid_type(
349/// Unexpected::Bool(v),
350/// &"a negative integer",
351/// ));
352/// # }
353/// ```
354pub trait Expected {
355 /// Format an explanation of what data was being expected. Same signature as
356 /// the `Display` and `Debug` traits.
357 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result;
358}
359
360impl<'de, T> Expected for T
361where
362 T: Visitor<'de>,
363{
364 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
365 self.expecting(formatter)
366 }
367}
368
369impl Expected for &str {
370 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
371 formatter.write_str(self)
372 }
373}
374
375impl Display for dyn Expected + '_ {
376 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
377 Expected::fmt(self, formatter)
378 }
379}
380
381////////////////////////////////////////////////////////////////////////////////
382
383/// A **data structure** that can be deserialized from any data format supported
384/// by Serde.
385///
386/// Serde provides `Deserialize` implementations for many Rust primitive and
387/// standard library types. The complete list is [here][crate::de]. All of these
388/// can be deserialized using Serde out of the box.
389///
390/// Additionally, Serde provides a procedural macro called `serde_derive` to
391/// automatically generate `Deserialize` implementations for structs and enums
392/// in your program. See the [derive section of the manual][derive] for how to
393/// use this.
394///
395/// In rare cases it may be necessary to implement `Deserialize` manually for
396/// some type in your program. See the [Implementing
397/// `Deserialize`][impl-deserialize] section of the manual for more about this.
398///
399/// Third-party crates may provide `Deserialize` implementations for types that
400/// they expose. For example the `linked-hash-map` crate provides a
401/// `LinkedHashMap<K, V>` type that is deserializable by Serde because the crate
402/// provides an implementation of `Deserialize` for it.
403///
404/// [derive]: https://serde.rs/derive.html
405/// [impl-deserialize]: https://serde.rs/impl-deserialize.html
406///
407/// # Lifetime
408///
409/// The `'de` lifetime of this trait is the lifetime of data that may be
410/// borrowed by `Self` when deserialized. See the page [Understanding
411/// deserializer lifetimes] for a more detailed explanation of these lifetimes.
412///
413/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
414pub trait Deserialize<'de>: Sized {
415 /// Deserialize this value from the given Serde deserializer.
416 ///
417 /// See the [Implementing `Deserialize`][impl-deserialize] section of the
418 /// manual for more information about how to implement this method.
419 ///
420 /// [impl-deserialize]: https://serde.rs/impl-deserialize.html
421 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
422 where
423 D: Deserializer<'de>;
424
425 /// Deserializes a value into `self` from the given Deserializer.
426 ///
427 /// The purpose of this method is to allow the deserializer to reuse
428 /// resources and avoid copies. As such, if this method returns an error,
429 /// `self` will be in an indeterminate state where some parts of the struct
430 /// have been overwritten. Although whatever state that is will be
431 /// memory-safe.
432 ///
433 /// This is generally useful when repeatedly deserializing values that
434 /// are processed one at a time, where the value of `self` doesn't matter
435 /// when the next deserialization occurs.
436 ///
437 /// If you manually implement this, your recursive deserializations should
438 /// use `deserialize_in_place`.
439 ///
440 /// This method is stable and an official public API, but hidden from the
441 /// documentation because it is almost never what newbies are looking for.
442 /// Showing it in rustdoc would cause it to be featured more prominently
443 /// than it deserves.
444 #[doc(hidden)]
445 fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>
446 where
447 D: Deserializer<'de>,
448 {
449 // Default implementation just delegates to `deserialize` impl.
450 *place = tri!(Deserialize::deserialize(deserializer));
451 Ok(())
452 }
453}
454
455/// A data structure that can be deserialized without borrowing any data from
456/// the deserializer.
457///
458/// This is primarily useful for trait bounds on functions. For example a
459/// `from_str` function may be able to deserialize a data structure that borrows
460/// from the input string, but a `from_reader` function may only deserialize
461/// owned data.
462///
463/// # Lifetime
464///
465/// The relationship between `Deserialize` and `DeserializeOwned` in trait
466/// bounds is explained in more detail on the page [Understanding deserializer
467/// lifetimes].
468///
469/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
470pub trait DeserializeOwned: for<'de> Deserialize<'de> {}
471impl<T> DeserializeOwned for T where T: for<'de> Deserialize<'de> {}
472
473/// `DeserializeSeed` is the stateful form of the `Deserialize` trait. If you
474/// ever find yourself looking for a way to pass data into a `Deserialize` impl,
475/// this trait is the way to do it.
476///
477/// As one example of stateful deserialization consider deserializing a JSON
478/// array into an existing buffer. Using the `Deserialize` trait we could
479/// deserialize a JSON array into a `Vec<T>` but it would be a freshly allocated
480/// `Vec<T>`; there is no way for `Deserialize` to reuse a previously allocated
481/// buffer. Using `DeserializeSeed` instead makes this possible as in the
482/// example code below.
483///
484/// In practice the majority of deserialization is stateless. An API expecting a
485/// seed can be appeased by passing `std::marker::PhantomData` as a seed in the
486/// case of stateless deserialization.
487///
488/// # Lifetime
489///
490/// The `'de` lifetime of this trait is the lifetime of data that may be
491/// borrowed by `Self::Value` when deserialized. See the page [Understanding
492/// deserializer lifetimes] for a more detailed explanation of these lifetimes.
493///
494/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
495pub trait DeserializeSeed<'de>: Sized {
496 /// The type produced by using this seed.
497 type Value;
498
499 /// Equivalent to the more common `Deserialize::deserialize` method, except
500 /// with some initial piece of data (the seed) passed in.
501 fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
502 where
503 D: Deserializer<'de>;
504}
505
506impl<'de, T> DeserializeSeed<'de> for PhantomData<T>
507where
508 T: Deserialize<'de>,
509{
510 type Value = T;
511
512 #[inline]
513 fn deserialize<D>(self, deserializer: D) -> Result<T, D::Error>
514 where
515 D: Deserializer<'de>,
516 {
517 T::deserialize(deserializer)
518 }
519}
520
521/////////////////////////////////////////////////////////////////////
522
523/// Deserializer
524pub trait Deserializer<'de>: Sized {
525 /// The error type that can be returned if some error occurs during
526 /// deserialization.
527 type Error: Error;
528
529 /// Hint that the `Deserialize` type is expecting the discriminant of an enum variant.
530 fn deserialize_identifier<V>(
531 self,
532 size: ReadEnumSize,
533 visitor: V,
534 ) -> Result<V::Value, Self::Error>
535 where
536 V: Visitor<'de>;
537
538 /// Deserialize map key.
539 ///
540 /// - It is mainly called to deserialize the key of a field when implementing [`Deserialize`] of struct.
541 /// - The most intended use is to parse XML name strings. The `key` part of `<hkparam name="key">`.
542 ///
543 /// The default implementation does nothing.
544 fn deserialize_key<V>(self, visitor: V) -> Result<V::Value, Self::Error>
545 where
546 V: Visitor<'de>,
547 {
548 visitor.visit_void(())
549 }
550
551 /// Deserialize class index.
552 fn deserialize_class_index<V>(self, visitor: V) -> Result<V::Value, Self::Error>
553 where
554 V: Visitor<'de>;
555
556 /// Deserialize a `Void` value.
557 ///
558 /// No type information.
559 ///
560 /// This is often used to fill in generics elements with types for which generics are not used.
561 ///
562 /// - `hkArray<hkBool>` -> `vtype`: `TYPE_ARRAY`, `vsubtype`: `TYPE_BOOL`
563 /// - `hkBool -> `vtype`: `TYPE_BOOL`, `vsubtype`: `TYPE_VOID`
564 /// - There is also a pattern `hkArray<void>`. The type information is unknown, but this member always contains the `SERIALIZE_IGNORED` flag and can be skipped.
565 fn deserialize_void<V>(self, visitor: V) -> Result<V::Value, Self::Error>
566 where
567 V: Visitor<'de>;
568
569 /// Deserialize a `bool` value.
570 fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
571 where
572 V: Visitor<'de>;
573
574 /// Deserialize an `char` value.
575 fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
576 where
577 V: Visitor<'de>;
578
579 /// Deserialize an `i8` value.
580 ///
581 /// If the format does not differentiate between `i8` and `i64`, a
582 /// reasonable implementation would be to cast the value to `i64` and
583 /// forward to `deserialize_i64`.
584 fn deserialize_int8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
585 where
586 V: Visitor<'de>;
587
588 /// Deserialize an `u8` value.
589 fn deserialize_uint8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
590 where
591 V: Visitor<'de>;
592
593 /// Deserialize an `i16` value.
594 fn deserialize_int16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
595 where
596 V: Visitor<'de>;
597
598 /// Deserialize an `u16` value.
599 fn deserialize_uint16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
600 where
601 V: Visitor<'de>;
602
603 /// Deserialize an `i32` value.
604 fn deserialize_int32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
605 where
606 V: Visitor<'de>;
607
608 /// Deserialize an `u32` value.
609 fn deserialize_uint32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
610 where
611 V: Visitor<'de>;
612
613 /// Deserialize an `i64` value.
614 fn deserialize_int64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
615 where
616 V: Visitor<'de>;
617
618 /// Deserialize an `u64` value.
619 fn deserialize_uint64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
620 where
621 V: Visitor<'de>;
622
623 /// Deserialize an `f32` value.
624 fn deserialize_real<V>(self, visitor: V) -> Result<V::Value, Self::Error>
625 where
626 V: Visitor<'de>;
627
628 /// Deserialize an `Vector4` value.
629 fn deserialize_vector4<V>(self, visitor: V) -> Result<V::Value, Self::Error>
630 where
631 V: Visitor<'de>;
632
633 /// Deserialize an `Quaternion` value.
634 fn deserialize_quaternion<V>(self, visitor: V) -> Result<V::Value, Self::Error>
635 where
636 V: Visitor<'de>;
637
638 /// Deserialize an `Matrix3` value.
639 fn deserialize_matrix3<V>(self, visitor: V) -> Result<V::Value, Self::Error>
640 where
641 V: Visitor<'de>;
642
643 /// Deserialize an `Rotation` value.
644 fn deserialize_rotation<V>(self, visitor: V) -> Result<V::Value, Self::Error>
645 where
646 V: Visitor<'de>;
647
648 /// Deserialize an `QsTransform` value.
649 fn deserialize_qstransform<V>(self, visitor: V) -> Result<V::Value, Self::Error>
650 where
651 V: Visitor<'de>;
652
653 /// Deserialize an `Matrix4` value.
654 fn deserialize_matrix4<V>(self, visitor: V) -> Result<V::Value, Self::Error>
655 where
656 V: Visitor<'de>;
657
658 /// Deserialize an `Transform` value.
659 fn deserialize_transform<V>(self, visitor: V) -> Result<V::Value, Self::Error>
660 where
661 V: Visitor<'de>;
662
663 /// Deserialize an `Pointer` value.
664 fn deserialize_pointer<V>(self, visitor: V) -> Result<V::Value, Self::Error>
665 where
666 V: Visitor<'de>;
667
668 /// Deserialize an `Array` value.
669 fn deserialize_array<V>(self, visitor: V) -> Result<V::Value, Self::Error>
670 where
671 V: Visitor<'de>;
672
673 /// Deserialize an fixed array(e.g. `[bool; 3]`) value.
674 ///
675 /// # Intention to separate methods
676 /// The methods for fixed size array(stack array) and `hkArray` binary data are separated because they have different metadata.
677 fn deserialize_fixed_array<V>(self, visitor: V) -> Result<V::Value, Self::Error>
678 where
679 V: Visitor<'de>;
680
681 /// Deserialize a Class Index Array value.
682 fn deserialize_class_index_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
683 where
684 V: Visitor<'de>;
685
686 /// Deserialize an `enum` value.
687 ///
688 /// Hint that the `Deserialize` type is expecting an enum value with a
689 /// particular name and possible variants.
690 fn deserialize_enum<V>(
691 self,
692 name: &'static str,
693 variants: &'static [&'static str],
694 visitor: V,
695 ) -> Result<V::Value, Self::Error>
696 where
697 V: Visitor<'de>;
698
699 /// Deserialize an `Struct` value.
700 fn deserialize_struct<V>(
701 self,
702 name: &'static str,
703 fields: &'static [&'static str],
704 visitor: V,
705 ) -> Result<V::Value, Self::Error>
706 where
707 V: Visitor<'de>;
708
709 /// Deserialize an `Variant` value.
710 ///
711 /// # Note
712 /// Never used(In the 2010 Havok classes)
713 ///
714 /// `hkVariant` is a structure with two pointers, but its identity is unknown,
715 /// so u128(`[u64; 2]`) of binary data is used as an argument instead. (If it is 32bit, you would need to cast it to u64(`[u32;2]`).)
716 fn deserialize_variant<V>(self, visitor: V) -> Result<V::Value, Self::Error>
717 where
718 V: Visitor<'de>;
719
720 /// Deserialize an `CString` value.
721 fn deserialize_cstring<V>(self, visitor: V) -> Result<V::Value, Self::Error>
722 where
723 V: Visitor<'de>;
724
725 /// Deserialize an `ULong`(pointer size(u32 or u64)) value.
726 fn deserialize_ulong<V>(self, visitor: V) -> Result<V::Value, Self::Error>
727 where
728 V: Visitor<'de>;
729
730 /// Deserialize an `Flags` value.
731 ///
732 /// Hint that the `Deserialize` type is expecting flags value with a
733 /// particular name and possible variants.
734 fn deserialize_flags<V>(self, size: ReadEnumSize, visitor: V) -> Result<V::Value, Self::Error>
735 where
736 V: Visitor<'de>;
737
738 /// Deserialize an `Half`(`f16`) value.
739 fn deserialize_half<V>(self, visitor: V) -> Result<V::Value, Self::Error>
740 where
741 V: Visitor<'de>;
742
743 /// Deserialize an `StringPtr` value.
744 fn deserialize_stringptr<V>(self, visitor: V) -> Result<V::Value, Self::Error>
745 where
746 V: Visitor<'de>;
747}
748
749////////////////////////////////////////////////////////////////////////////////
750
751/// This trait represents a visitor that walks through a deserializer.
752///
753/// # Lifetime
754///
755/// The `'de` lifetime of this trait is the requirement for lifetime of data
756/// that may be borrowed by `Self::Value`. See the page [Understanding
757/// deserializer lifetimes] for a more detailed explanation of these lifetimes.
758///
759/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
760pub trait Visitor<'de>: Sized {
761 /// The value produced by this visitor.
762 type Value;
763
764 /// Format a message stating what data this Visitor expects to receive.
765 ///
766 /// This is used in error messages. The message should complete the sentence
767 /// "This Visitor expects to receive ...", for example the message could be
768 /// "an integer between 0 and 64". The message should not be capitalized and
769 /// should not end with a period.
770 ///
771 /// ```edition2021
772 /// # use std::fmt;
773 /// #
774 /// # struct S {
775 /// # max: usize,
776 /// # }
777 /// #
778 /// # impl<'de> havok_serde::de::Visitor<'de> for S {
779 /// # type Value = ();
780 /// #
781 /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
782 /// write!(formatter, "an integer between 0 and {}", self.max)
783 /// }
784 /// # }
785 /// ```
786 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result;
787
788 /// The input contains a [`MapAccess`] key.
789 ///
790 /// The default implementation fails with a type error.
791 fn visit_key<E>(self, key: &str) -> Result<Self::Value, E>
792 where
793 E: Error,
794 {
795 let _ = key;
796 Err(Error::invalid_type(Unexpected::Other(key), &self))
797 }
798
799 /// The input contains a havok class.
800 ///
801 /// The default implementation fails with a type error.
802 fn visit_class_index<A>(self, map: A) -> Result<Self::Value, A::Error>
803 where
804 A: ClassIndexAccess<'de>,
805 {
806 let _ = map;
807 Err(Error::invalid_type(Unexpected::Struct, &self))
808 }
809
810 /// The input contains a void.
811 ///
812 /// The default implementation fails with a type error.
813 fn visit_void<E>(self, _: ()) -> Result<Self::Value, E>
814 where
815 E: Error,
816 {
817 Err(Error::invalid_type(Unexpected::Void, &self))
818 }
819
820 /// The input contains a boolean.
821 ///
822 /// The default implementation fails with a type error.
823 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
824 where
825 E: Error,
826 {
827 Err(Error::invalid_type(Unexpected::Bool(v), &self))
828 }
829
830 /// The input contains char.
831 ///
832 /// The default implementation fails with a type error.
833 fn visit_char<E>(self, v: char) -> Result<Self::Value, E>
834 where
835 E: Error,
836 {
837 Err(Error::invalid_type(Unexpected::Char(v), &self))
838 }
839
840 /// The input contains a i8.
841 ///
842 /// The default implementation fails with a type error.
843 fn visit_int8<E>(self, v: i8) -> Result<Self::Value, E>
844 where
845 E: Error,
846 {
847 Err(Error::invalid_type(Unexpected::Int8(v), &self))
848 }
849
850 /// The input contains a u8.
851 ///
852 /// The default implementation fails with a type error.
853 fn visit_uint8<E>(self, v: u8) -> Result<Self::Value, E>
854 where
855 E: Error,
856 {
857 Err(Error::invalid_type(Unexpected::Uint8(v), &self))
858 }
859
860 /// The input contains a i16.
861 ///
862 /// The default implementation fails with a type error.
863 fn visit_int16<E>(self, v: i16) -> Result<Self::Value, E>
864 where
865 E: Error,
866 {
867 Err(Error::invalid_type(Unexpected::Int16(v), &self))
868 }
869
870 /// The input contains a u16.
871 ///
872 /// The default implementation fails with a type error.
873 fn visit_uint16<E>(self, v: u16) -> Result<Self::Value, E>
874 where
875 E: Error,
876 {
877 Err(Error::invalid_type(Unexpected::Uint16(v), &self))
878 }
879
880 /// The input contains a i32.
881 ///
882 /// The default implementation fails with a type error.
883 fn visit_int32<E>(self, v: i32) -> Result<Self::Value, E>
884 where
885 E: Error,
886 {
887 Err(Error::invalid_type(Unexpected::Int32(v), &self))
888 }
889
890 /// The input contains a u32.
891 ///
892 /// The default implementation fails with a type error.
893 fn visit_uint32<E>(self, v: u32) -> Result<Self::Value, E>
894 where
895 E: Error,
896 {
897 Err(Error::invalid_type(Unexpected::Uint32(v), &self))
898 }
899
900 /// The input contains a i64.
901 ///
902 /// The default implementation fails with a type error.
903 fn visit_int64<E>(self, v: i64) -> Result<Self::Value, E>
904 where
905 E: Error,
906 {
907 Err(Error::invalid_type(Unexpected::Int64(v), &self))
908 }
909
910 /// The input contains a u64.
911 ///
912 /// The default implementation fails with a type error.
913 fn visit_uint64<E>(self, v: u64) -> Result<Self::Value, E>
914 where
915 E: Error,
916 {
917 Err(Error::invalid_type(Unexpected::Uint64(v), &self))
918 }
919
920 /// The input contains a f32.
921 ///
922 /// The default implementation fails with a type error.
923 fn visit_real<E>(self, v: f32) -> Result<Self::Value, E>
924 where
925 E: Error,
926 {
927 Err(Error::invalid_type(Unexpected::Real(v), &self))
928 }
929
930 /// The input contains a Vector4.
931 ///
932 /// The default implementation fails with a type error.
933 fn visit_vector4<E>(self, v: Vector4) -> Result<Self::Value, E>
934 where
935 E: Error,
936 {
937 Err(Error::invalid_type(Unexpected::Vector4(v), &self))
938 }
939
940 /// The input contains a Quaternion.
941 ///
942 /// The default implementation fails with a type error.
943 fn visit_quaternion<E>(self, v: Quaternion) -> Result<Self::Value, E>
944 where
945 E: Error,
946 {
947 Err(Error::invalid_type(Unexpected::Quaternion(v), &self))
948 }
949
950 /// The input contains a Matrix3.
951 ///
952 /// The default implementation fails with a type error.
953 fn visit_matrix3<E>(self, v: Matrix3) -> Result<Self::Value, E>
954 where
955 E: Error,
956 {
957 Err(Error::invalid_type(Unexpected::Matrix3(v), &self))
958 }
959
960 /// The input contains a Rotation.
961 ///
962 /// The default implementation fails with a type error.
963 fn visit_rotation<E>(self, v: Rotation) -> Result<Self::Value, E>
964 where
965 E: Error,
966 {
967 Err(Error::invalid_type(Unexpected::Rotation(v), &self))
968 }
969
970 /// The input contains a QsTransform.
971 ///
972 /// The default implementation fails with a type error.
973 fn visit_qstransform<E>(self, v: QsTransform) -> Result<Self::Value, E>
974 where
975 E: Error,
976 {
977 Err(Error::invalid_type(Unexpected::QsTransform(v), &self))
978 }
979
980 /// The input contains a Matrix4.
981 ///
982 /// The default implementation fails with a type error.
983 fn visit_matrix4<E>(self, v: Matrix4) -> Result<Self::Value, E>
984 where
985 E: Error,
986 {
987 Err(Error::invalid_type(Unexpected::Matrix4(v), &self))
988 }
989
990 /// The input contains a Transform.
991 ///
992 /// The default implementation fails with a type error.
993 fn visit_transform<E>(self, v: Transform) -> Result<Self::Value, E>
994 where
995 E: Error,
996 {
997 Err(Error::invalid_type(Unexpected::Transform(v), &self))
998 }
999
1000 /// The input contains a Pointer.
1001 ///
1002 /// The default implementation fails with a type error.
1003 fn visit_pointer<E>(self, v: Pointer) -> Result<Self::Value, E>
1004 where
1005 E: Error,
1006 {
1007 Err(Error::invalid_type(Unexpected::Pointer(v), &self))
1008 }
1009
1010 /// The input contains a Variant.
1011 ///
1012 /// The default implementation fails with a type error.
1013 fn visit_variant<E>(self, v: Variant) -> Result<Self::Value, E>
1014 where
1015 E: Error,
1016 {
1017 Err(Error::invalid_type(Unexpected::Variant(v), &self))
1018 }
1019
1020 /// The input contains an Array.
1021 ///
1022 /// The default implementation fails with a type error.
1023 fn visit_array<A>(self, seq: A) -> Result<Self::Value, A::Error>
1024 where
1025 A: SeqAccess<'de>,
1026 {
1027 let _ = seq;
1028 Err(Error::invalid_type(Unexpected::Array, &self))
1029 }
1030
1031 /// The input contains an enum.
1032 ///
1033 /// The default implementation fails with a type error.
1034 fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
1035 where
1036 A: EnumAccess<'de>,
1037 {
1038 let _ = data;
1039 Err(Error::invalid_type(Unexpected::Enum, &self))
1040 }
1041
1042 /// The input contains a key-value map.(serde: `visit_map`)
1043 ///
1044 /// The default implementation fails with a type error.
1045 ///
1046 /// # Note
1047 /// This is a separated method because bytes processing cannot coexist with XML's `SERIALIZE_IGNORED`.
1048 fn visit_struct<A>(self, map: A) -> Result<Self::Value, A::Error>
1049 where
1050 A: MapAccess<'de>,
1051 {
1052 let _ = map;
1053 Err(Error::invalid_type(Unexpected::Struct, &self))
1054 }
1055
1056 /// The input contains a key-value map.(serde: `visit_map`)
1057 ///
1058 /// The default implementation fails with a type error.
1059 ///
1060 /// # Note
1061 /// This is a separated method because bytes processing cannot coexist with XML's `SERIALIZE_IGNORED`.
1062 fn visit_struct_for_bytes<A>(self, map: A) -> Result<Self::Value, A::Error>
1063 where
1064 A: MapAccess<'de>,
1065 {
1066 let _ = map;
1067 Err(Error::invalid_type(Unexpected::Struct, &self))
1068 }
1069
1070 /// The input contains a CString.
1071 ///
1072 /// The default implementation fails with a type error.
1073 fn visit_cstring<E>(self, v: CString<'de>) -> Result<Self::Value, E>
1074 where
1075 E: Error,
1076 {
1077 Err(Error::invalid_type(Unexpected::CString(v), &self))
1078 }
1079
1080 /// The input contains a u64.
1081 ///
1082 /// The default implementation fails with a type error.
1083 fn visit_ulong<E>(self, v: Ulong) -> Result<Self::Value, E>
1084 where
1085 E: Error,
1086 {
1087 Err(Error::invalid_type(Unexpected::Ulong(v), &self))
1088 }
1089
1090 /// The input contains flags.
1091 ///
1092 /// The default implementation fails with a type error.
1093 fn visit_flags<A>(self, data: A) -> Result<Self::Value, A::Error>
1094 where
1095 A: EnumAccess<'de>,
1096 {
1097 let _ = data;
1098 Err(Error::invalid_type(Unexpected::Flags, &self))
1099 }
1100
1101 /// The input contains a f16.
1102 ///
1103 /// The default implementation fails with a type error.
1104 fn visit_half<E>(self, v: f16) -> Result<Self::Value, E>
1105 where
1106 E: Error,
1107 {
1108 Err(Error::invalid_type(Unexpected::Half(v), &self))
1109 }
1110
1111 /// The input contains a StringPtr.
1112 ///
1113 /// The default implementation fails with a type error.
1114 fn visit_stringptr<E>(self, v: StringPtr<'de>) -> Result<Self::Value, E>
1115 where
1116 E: Error,
1117 {
1118 Err(Error::invalid_type(Unexpected::StringPtr(v), &self))
1119 }
1120}
1121
1122////////////////////////////////////////////////////////////////////////////////
1123
1124/// Provides a `Visitor` access to each element of a sequence in the input.
1125///
1126/// This is a trait that a `Deserializer` passes to a `Visitor` implementation,
1127/// which deserializes each item in a sequence.
1128///
1129/// # Lifetime
1130///
1131/// The `'de` lifetime of this trait is the lifetime of data that may be
1132/// borrowed by deserialized sequence elements. See the page [Understanding
1133/// deserializer lifetimes] for a more detailed explanation of these lifetimes.
1134///
1135/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
1136///
1137/// # Example implementation
1138///
1139/// The [example data format] presented on the website demonstrates an
1140/// implementation of `SeqAccess` for a basic JSON data format.
1141///
1142/// [example data format]: https://serde.rs/data-format.html
1143pub trait SeqAccess<'de> {
1144 /// The error type that can be returned if some error occurs during
1145 /// deserialization.
1146 type Error: Error;
1147
1148 /// Get current class index attribute(XML: e.g. `#0050`) for key of [`HashMap`]
1149 fn class_ptr(&self) -> Result<usize, Self::Error>;
1150
1151 /// This returns `Ok(Some(value))` for the next value in the sequence, or
1152 /// `Ok(None)` if there are no more remaining items.
1153 ///
1154 /// `Deserialize` implementations should typically use
1155 /// `SeqAccess::next_primitive_element` instead.
1156 fn next_primitive_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1157 where
1158 T: DeserializeSeed<'de>;
1159
1160 /// This returns `Ok(Some(value))` for the next value in the sequence, or
1161 /// `Ok(None)` if there are no more remaining items.
1162 ///
1163 /// `Deserialize` implementations should typically use
1164 /// `SeqAccess::next_class_element` instead.
1165 fn next_class_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1166 where
1167 T: DeserializeSeed<'de>; // + crate::HavokClass
1168
1169 /// This returns `Ok(Some(value))` for the next value in the sequence, or
1170 /// `Ok(None)` if there are no more remaining items.
1171 ///
1172 /// `Deserialize` implementations should typically use
1173 /// `SeqAccess::next_math_element` instead.
1174 fn next_math_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1175 where
1176 T: DeserializeSeed<'de>;
1177
1178 /// This returns `Ok(Some(value))` for the next value in the sequence, or
1179 /// `Ok(None)` if there are no more remaining items.
1180 ///
1181 /// `Deserialize` implementations should typically use
1182 /// `SeqAccess::next_cstring_element` instead.
1183 fn next_cstring_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1184 where
1185 T: DeserializeSeed<'de>;
1186
1187 /// This returns `Ok(Some(value))` for the next value in the sequence, or
1188 /// `Ok(None)` if there are no more remaining items.
1189 ///
1190 /// `Deserialize` implementations should typically use
1191 /// `SeqAccess::next_stringptr_element` instead.
1192 fn next_stringptr_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1193 where
1194 T: DeserializeSeed<'de>;
1195
1196 /// This returns `Ok(Some(value))` for the next value in the sequence, or
1197 /// `Ok(None)` if there are no more remaining items.
1198 ///
1199 /// This method exists as a convenience for `Deserialize` implementations.
1200 /// `SeqAccess` implementations should not override the default behavior.
1201 #[inline]
1202 fn next_primitive_element<T>(&mut self) -> Result<Option<T>, Self::Error>
1203 where
1204 T: Deserialize<'de>,
1205 {
1206 self.next_primitive_element_seed(PhantomData)
1207 }
1208
1209 /// This returns `Ok(Some(value))` for the next value in the sequence, or
1210 /// `Ok(None)` if there are no more remaining items.
1211 ///
1212 /// This method exists as a convenience for `Deserialize` implementations.
1213 /// `SeqAccess` implementations should not override the default behavior.
1214 #[inline]
1215 fn next_class_element<T>(&mut self) -> Result<Option<T>, Self::Error>
1216 where
1217 T: Deserialize<'de> + crate::HavokClass,
1218 {
1219 self.next_class_element_seed(PhantomData)
1220 }
1221
1222 /// This returns `Ok(Some(value))` for the next value in the sequence, or
1223 /// `Ok(None)` if there are no more remaining items.
1224 ///
1225 /// This method exists as a convenience for `Deserialize` implementations.
1226 /// `SeqAccess` implementations should not override the default behavior.
1227 #[inline]
1228 fn next_math_element<T>(&mut self) -> Result<Option<T>, Self::Error>
1229 where
1230 T: Deserialize<'de>,
1231 {
1232 self.next_math_element_seed(PhantomData)
1233 }
1234
1235 /// This returns `Ok(Some(value))` for the next value in the sequence, or
1236 /// `Ok(None)` if there are no more remaining items.
1237 ///
1238 /// This method exists as a convenience for `Deserialize` implementations.
1239 /// `SeqAccess` implementations should not override the default behavior.
1240 #[inline]
1241 fn next_cstring_element(&mut self) -> Result<Option<CString<'de>>, Self::Error> {
1242 self.next_cstring_element_seed(PhantomData)
1243 }
1244
1245 /// This returns `Ok(Some(value))` for the next value in the sequence, or
1246 /// `Ok(None)` if there are no more remaining items.
1247 ///
1248 /// This method exists as a convenience for `Deserialize` implementations.
1249 /// `SeqAccess` implementations should not override the default behavior.
1250 #[inline]
1251 fn next_stringptr_element(&mut self) -> Result<Option<StringPtr<'de>>, Self::Error> {
1252 self.next_stringptr_element_seed(PhantomData)
1253 }
1254
1255 /// Returns the number of elements remaining in the sequence, if known.
1256 #[inline]
1257 fn size_hint(&self) -> Option<usize> {
1258 None
1259 }
1260}
1261
1262// NOTE: Deref does not result in a circular call error for `&mut A` because it calls the method of A.
1263impl<'de, A> SeqAccess<'de> for &mut A
1264where
1265 A: ?Sized + SeqAccess<'de>,
1266{
1267 type Error = A::Error;
1268
1269 #[inline]
1270 fn class_ptr(&self) -> Result<usize, Self::Error> {
1271 (**self).class_ptr()
1272 }
1273
1274 #[inline]
1275 fn next_primitive_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1276 where
1277 T: DeserializeSeed<'de>,
1278 {
1279 (**self).next_primitive_element_seed(seed)
1280 }
1281
1282 #[inline]
1283 fn next_class_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1284 where
1285 T: DeserializeSeed<'de>,
1286 {
1287 (**self).next_class_element_seed(seed)
1288 }
1289
1290 #[inline]
1291 fn next_math_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1292 where
1293 T: DeserializeSeed<'de>,
1294 {
1295 (**self).next_math_element_seed(seed)
1296 }
1297
1298 fn next_cstring_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1299 where
1300 T: DeserializeSeed<'de>,
1301 {
1302 (**self).next_cstring_element_seed(seed)
1303 }
1304
1305 fn next_stringptr_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1306 where
1307 T: DeserializeSeed<'de>,
1308 {
1309 (**self).next_stringptr_element_seed(seed)
1310 }
1311
1312 #[inline]
1313 fn next_primitive_element<T>(&mut self) -> Result<Option<T>, Self::Error>
1314 where
1315 T: Deserialize<'de>,
1316 {
1317 (**self).next_primitive_element()
1318 }
1319
1320 #[inline]
1321 fn size_hint(&self) -> Option<usize> {
1322 (**self).size_hint()
1323 }
1324}
1325
1326////////////////////////////////////////////////////////////////////////////////
1327
1328/// Provides a `Visitor` access to each entry of a map in the input.
1329///
1330/// This is a trait that a `Deserializer` passes to a `Visitor` implementation.
1331///
1332/// # Lifetime
1333///
1334/// The `'de` lifetime of this trait is the lifetime of data that may be
1335/// borrowed by deserialized map entries. See the page [Understanding
1336/// deserializer lifetimes] for a more detailed explanation of these lifetimes.
1337///
1338/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
1339///
1340/// # Example implementation
1341///
1342/// The [example data format] presented on the website demonstrates an
1343/// implementation of `MapAccess` for a basic JSON data format.
1344///
1345/// [example data format]: https://serde.rs/data-format.html
1346pub trait MapAccess<'de> {
1347 /// The error type that can be returned if some error occurs during
1348 /// deserialization.
1349 type Error: Error;
1350
1351 /// Get this class pointer name (e.g. `Pointer::new(1`)
1352 fn class_ptr(&mut self) -> Option<Pointer>;
1353
1354 /// - Skip reading the current position of binary data by pad minutes.
1355 /// - The XML deserializer does nothing.
1356 ///
1357 /// The default implementation does nothing.
1358 #[inline]
1359 fn pad(&mut self, x86_pad: usize, x64_pad: usize) -> Result<(), Self::Error> {
1360 let _ = x86_pad;
1361 let _ = x64_pad;
1362 Ok(())
1363 }
1364
1365 /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)`
1366 /// if there are no more remaining entries.
1367 ///
1368 /// `Deserialize` implementations should typically use
1369 /// `MapAccess::next_key` or `MapAccess::next_entry` instead.
1370 fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
1371 where
1372 K: DeserializeSeed<'de>;
1373
1374 /// This returns a `Ok(value)` for the next value in the map.
1375 ///
1376 /// `Deserialize` implementations should typically use
1377 /// `MapAccess::next_value` instead.
1378 fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
1379 where
1380 V: DeserializeSeed<'de>;
1381
1382 /// `Deserialize` implementations should typically use
1383 /// `MapAccess::skip_value` instead.
1384 ///
1385 /// # Primary use.
1386 /// Clean up after the XML tag when unwanted items come in.
1387 fn skip_value_seed(&mut self) -> Result<(), Self::Error>;
1388
1389 /// Deserialize C++ inherited parent fields(for bytes method)
1390 ///
1391 /// This returns a `Ok(value)` for the next value in the map.
1392 ///
1393 /// `Deserialize` implementations should typically use
1394 /// `MapAccess::next_value` instead.
1395 fn parent_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
1396 where
1397 V: DeserializeSeed<'de>;
1398
1399 /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in
1400 /// the map, or `Ok(None)` if there are no more remaining items.
1401 ///
1402 /// `MapAccess` implementations should override the default behavior if a
1403 /// more efficient implementation is possible.
1404 ///
1405 /// `Deserialize` implementations should typically use
1406 /// `MapAccess::next_entry` instead.
1407 #[allow(clippy::type_complexity)]
1408 #[inline]
1409 fn next_entry_seed<K, V>(
1410 &mut self,
1411 kseed: K,
1412 vseed: V,
1413 ) -> Result<Option<(K::Value, V::Value)>, Self::Error>
1414 where
1415 K: DeserializeSeed<'de>,
1416 V: DeserializeSeed<'de>,
1417 {
1418 match tri!(self.next_key_seed(kseed)) {
1419 Some(key) => {
1420 let value = tri!(self.next_value_seed(vseed));
1421 Ok(Some((key, value)))
1422 }
1423 None => Ok(None),
1424 }
1425 }
1426
1427 /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)`
1428 /// if there are no more remaining entries.
1429 ///
1430 /// This method exists as a convenience for `Deserialize` implementations.
1431 /// `MapAccess` implementations should not override the default behavior.
1432 #[inline]
1433 fn next_key<K>(&mut self) -> Result<Option<K>, Self::Error>
1434 where
1435 K: Deserialize<'de>,
1436 {
1437 self.next_key_seed(PhantomData)
1438 }
1439
1440 /// This returns a `Ok(value)` for the next value in the map.
1441 ///
1442 /// This method exists as a convenience for `Deserialize` implementations.
1443 /// `MapAccess` implementations should not override the default behavior.
1444 #[inline]
1445 fn next_value<V>(&mut self) -> Result<V, Self::Error>
1446 where
1447 V: Deserialize<'de>,
1448 {
1449 self.next_value_seed(PhantomData)
1450 }
1451
1452 /// This returns a `Ok(())` for the skip value in the map.
1453 ///
1454 /// # Primary use.
1455 /// Clean up after the XML tag when unwanted items come in.
1456 #[inline]
1457 fn skip_value(&mut self) -> Result<(), Self::Error> {
1458 self.skip_value_seed()
1459 }
1460
1461 /// Deserialize C++ inherited parent fields(for bytes method)
1462 ///
1463 /// This returns a `Ok(value)` for the next value in the map.
1464 ///
1465 /// This method exists as a convenience for `Deserialize` implementations.
1466 /// `MapAccess` implementations should not override the default behavior.
1467 fn parent_value<V>(&mut self) -> Result<V, Self::Error>
1468 where
1469 V: Deserialize<'de>,
1470 {
1471 self.parent_value_seed(PhantomData)
1472 }
1473
1474 /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in
1475 /// the map, or `Ok(None)` if there are no more remaining items.
1476 ///
1477 /// This method exists as a convenience for `Deserialize` implementations.
1478 /// `MapAccess` implementations should not override the default behavior.
1479 #[inline]
1480 fn next_entry<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error>
1481 where
1482 K: Deserialize<'de>,
1483 V: Deserialize<'de>,
1484 {
1485 self.next_entry_seed(PhantomData, PhantomData)
1486 }
1487
1488 /// Returns the number of entries remaining in the map, if known.
1489 #[inline]
1490 fn size_hint(&self) -> Option<usize> {
1491 None
1492 }
1493}
1494
1495impl<'de, A> MapAccess<'de> for &mut A
1496where
1497 A: ?Sized + MapAccess<'de>,
1498{
1499 type Error = A::Error;
1500
1501 #[inline]
1502 fn class_ptr(&mut self) -> Option<Pointer> {
1503 (**self).class_ptr()
1504 }
1505
1506 #[inline]
1507 fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
1508 where
1509 K: DeserializeSeed<'de>,
1510 {
1511 (**self).next_key_seed(seed)
1512 }
1513
1514 #[inline]
1515 fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
1516 where
1517 V: DeserializeSeed<'de>,
1518 {
1519 (**self).next_value_seed(seed)
1520 }
1521
1522 #[inline]
1523 fn skip_value_seed(&mut self) -> Result<(), Self::Error> {
1524 (**self).skip_value_seed()
1525 }
1526
1527 #[inline]
1528 fn parent_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
1529 where
1530 V: DeserializeSeed<'de>,
1531 {
1532 (**self).parent_value_seed(seed)
1533 }
1534
1535 #[inline]
1536 fn next_entry_seed<K, V>(
1537 &mut self,
1538 kseed: K,
1539 vseed: V,
1540 ) -> Result<Option<(K::Value, V::Value)>, Self::Error>
1541 where
1542 K: DeserializeSeed<'de>,
1543 V: DeserializeSeed<'de>,
1544 {
1545 (**self).next_entry_seed(kseed, vseed)
1546 }
1547
1548 #[inline]
1549 fn next_entry<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error>
1550 where
1551 K: Deserialize<'de>,
1552 V: Deserialize<'de>,
1553 {
1554 (**self).next_entry()
1555 }
1556
1557 #[inline]
1558 fn next_key<K>(&mut self) -> Result<Option<K>, Self::Error>
1559 where
1560 K: Deserialize<'de>,
1561 {
1562 (**self).next_key()
1563 }
1564
1565 #[inline]
1566 fn next_value<V>(&mut self) -> Result<V, Self::Error>
1567 where
1568 V: Deserialize<'de>,
1569 {
1570 (**self).next_value()
1571 }
1572
1573 #[inline]
1574 fn skip_value(&mut self) -> Result<(), Self::Error> {
1575 (**self).next_value()
1576 }
1577
1578 #[inline]
1579 fn parent_value<V>(&mut self) -> Result<V, Self::Error>
1580 where
1581 V: Deserialize<'de>,
1582 {
1583 (**self).parent_value()
1584 }
1585
1586 #[inline]
1587 fn size_hint(&self) -> Option<usize> {
1588 (**self).size_hint()
1589 }
1590}
1591
1592////////////////////////////////////////////////////////////////////////////////
1593
1594/// Class Indexed Deserializer trait
1595pub trait ClassIndexAccess<'de> {
1596 /// Class name Error
1597 type Error: Error;
1598
1599 /// next class name.
1600 fn next_key(&mut self) -> Result<&'de str, Self::Error>;
1601
1602 /// deserialize class method.
1603 fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
1604 where
1605 V: DeserializeSeed<'de>;
1606
1607 /// Deserialize class method
1608 #[inline]
1609 fn next_value<V>(&mut self) -> Result<V, Self::Error>
1610 where
1611 V: Deserialize<'de>,
1612 {
1613 self.next_value_seed(PhantomData)
1614 }
1615}
1616
1617impl<'de, A> ClassIndexAccess<'de> for &mut A
1618where
1619 A: ?Sized + ClassIndexAccess<'de>,
1620{
1621 type Error = A::Error;
1622
1623 #[inline]
1624 fn next_key(&mut self) -> Result<&'de str, Self::Error> {
1625 (**self).next_key()
1626 }
1627
1628 #[inline]
1629 fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
1630 where
1631 V: DeserializeSeed<'de>,
1632 {
1633 (**self).next_value_seed(seed)
1634 }
1635
1636 #[inline]
1637 fn next_value<V>(&mut self) -> Result<V, Self::Error>
1638 where
1639 V: Deserialize<'de>,
1640 {
1641 self.next_value_seed(PhantomData)
1642 }
1643}
1644
1645////////////////////////////////////////////////////////////////////////////////
1646
1647/// Size to read to deserialize `enum` and `flags`.
1648/// This is used to deserialize binary data
1649pub enum ReadEnumSize {
1650 /// Deserialize binary data from i8
1651 Int8,
1652 /// Deserialize binary data from i16
1653 Int16,
1654 /// Deserialize binary data from i32
1655 Int32,
1656 /// Deserialize binary data from i64
1657 Int64,
1658 /// Deserialize binary data from u8
1659 Uint8,
1660 /// Deserialize binary data from u16
1661 Uint16,
1662 /// Deserialize binary data from u32
1663 Uint32,
1664 /// Deserialize binary data from u64
1665 Uint64,
1666}
1667
1668/// Provides a `Visitor` access to the data of an enum in the input.
1669///
1670/// `EnumAccess` is created by the `Deserializer` and passed to the
1671/// `Visitor` in order to identify which variant of an enum to deserialize.
1672///
1673/// # Lifetime
1674///
1675/// The `'de` lifetime of this trait is the lifetime of data that may be
1676/// borrowed by the deserialized enum variant. See the page [Understanding
1677/// deserializer lifetimes] for a more detailed explanation of these lifetimes.
1678///
1679/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
1680///
1681/// # Example implementation
1682///
1683/// The [example data format] presented on the website demonstrates an
1684/// implementation of `EnumAccess` for a basic JSON data format.
1685///
1686/// [example data format]: https://serde.rs/data-format.html
1687pub trait EnumAccess<'de>: Sized {
1688 /// The error type that can be returned if some error occurs during
1689 /// deserialization.
1690 type Error: Error;
1691 /// The `Visitor` that will be used to deserialize the content of the enum
1692 /// variant.
1693 type Variant: VariantAccess<'de, Error = Self::Error>;
1694
1695 /// `variant` is called to identify which variant to deserialize.
1696 ///
1697 /// `Deserialize` implementations should typically use `EnumAccess::variant`
1698 /// instead.
1699 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
1700 where
1701 V: DeserializeSeed<'de>;
1702
1703 /// `variant` is called to identify which variant to deserialize.
1704 ///
1705 /// This method exists as a convenience for `Deserialize` implementations.
1706 /// `EnumAccess` implementations should not override the default behavior.
1707 #[inline]
1708 fn variant<V>(self) -> Result<(V, Self::Variant), Self::Error>
1709 where
1710 V: Deserialize<'de>,
1711 {
1712 self.variant_seed(PhantomData)
1713 }
1714}
1715
1716/// `VariantAccess` is a visitor that is created by the `Deserializer` and
1717/// passed to the `Deserialize` to deserialize the content of a particular enum
1718/// variant.
1719///
1720/// # Lifetime
1721///
1722/// The `'de` lifetime of this trait is the lifetime of data that may be
1723/// borrowed by the deserialized enum variant. See the page [Understanding
1724/// deserializer lifetimes] for a more detailed explanation of these lifetimes.
1725///
1726/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
1727///
1728/// # Example implementation
1729///
1730/// The [example data format] presented on the website demonstrates an
1731/// implementation of `VariantAccess` for a basic JSON data format.
1732///
1733/// [example data format]: https://serde.rs/data-format.html
1734pub trait VariantAccess<'de>: Sized {
1735 /// The error type that can be returned if some error occurs during
1736 /// deserialization. Must match the error type of our `EnumAccess`.
1737 type Error: Error;
1738
1739 /// Called when deserializing a variant with no values.
1740 ///
1741 /// Check that the value of the enum is of a valid type immediately after deserialization with `EnumAccess::variant`.
1742 fn unit_variant(self) -> Result<(), Self::Error>;
1743}
1744
1745////////////////////////////////////////////////////////////////////////////////
1746
1747/// Used in error messages.
1748///
1749/// - expected `a`
1750/// - expected `a` or `b`
1751/// - expected one of `a`, `b`, `c`
1752///
1753/// The slice of names must not be empty.
1754struct OneOf {
1755 names: &'static [&'static str],
1756}
1757
1758impl Display for OneOf {
1759 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1760 match self.names.len() {
1761 0 => panic!(), // special case elsewhere
1762 1 => write!(formatter, "`{}`", self.names[0]),
1763 2 => write!(formatter, "`{}` or `{}`", self.names[0], self.names[1]),
1764 _ => {
1765 tri!(formatter.write_str("one of "));
1766 for (i, alt) in self.names.iter().enumerate() {
1767 if i > 0 {
1768 tri!(formatter.write_str(", "));
1769 }
1770 tri!(write!(formatter, "`{}`", alt));
1771 }
1772 Ok(())
1773 }
1774 }
1775 }
1776}