aldrin_core/
unknown_variant.rs1#[cfg(test)]
2mod test;
3
4use crate::tags::{self, Tag};
5use crate::{
6 Deserialize, DeserializeError, DeserializePrimary, Enum, Serialize, SerializedValue,
7 SerializedValueSlice,
8};
9use std::convert::Infallible;
10
11pub trait AsUnknownVariant {
12 type Value: Serialize<tags::Value>;
13
14 fn id(&self) -> u32;
15 fn value(self) -> Self::Value;
16}
17
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct UnknownVariant {
20 id: u32,
21 value: SerializedValue,
22}
23
24impl UnknownVariant {
25 pub fn new(id: u32, value: SerializedValue) -> Self {
26 Self { id, value }
27 }
28
29 pub fn id(&self) -> u32 {
30 self.id
31 }
32
33 pub fn value(&self) -> &SerializedValueSlice {
34 &self.value
35 }
36
37 pub fn into_value(self) -> SerializedValue {
38 self.value
39 }
40
41 pub fn deserialize_as<T: Tag, U: Deserialize<T>>(&self) -> Result<U, DeserializeError> {
42 self.value.deserialize_as()
43 }
44
45 pub fn deserialize<T: DeserializePrimary>(&self) -> Result<T, DeserializeError> {
46 self.deserialize_as()
47 }
48
49 pub fn deserialize_as_value(&self) -> Result<Enum, DeserializeError> {
50 self.deserialize()
51 }
52}
53
54impl AsUnknownVariant for UnknownVariant {
55 type Value = SerializedValue;
56
57 fn id(&self) -> u32 {
58 self.id
59 }
60
61 fn value(self) -> Self::Value {
62 self.value
63 }
64}
65
66impl<'a> AsUnknownVariant for &'a UnknownVariant {
67 type Value = &'a SerializedValueSlice;
68
69 fn id(&self) -> u32 {
70 self.id
71 }
72
73 fn value(self) -> Self::Value {
74 &self.value
75 }
76}
77
78#[derive(Debug, Copy, Clone)]
79pub struct UnknownVariantRef<T> {
80 pub id: u32,
81 pub value: T,
82}
83
84impl<T> UnknownVariantRef<T> {
85 pub fn new(id: u32, value: T) -> Self {
86 Self { id, value }
87 }
88}
89
90impl<T: Serialize<tags::Value>> AsUnknownVariant for UnknownVariantRef<T> {
91 type Value = T;
92
93 fn id(&self) -> u32 {
94 self.id
95 }
96
97 fn value(self) -> Self::Value {
98 self.value
99 }
100}
101
102impl AsUnknownVariant for Infallible {
103 type Value = Self;
104
105 fn id(&self) -> u32 {
106 match *self {}
107 }
108
109 fn value(self) -> Self::Value {
110 self
111 }
112}