Skip to main content

pytorch_reader/nested/
data.rs

1use std::collections::HashMap;
2
3use core::fmt;
4use num_traits::cast::ToPrimitive;
5
6/// The main data structure used for deserialization.
7///
8/// It can hold tree-like structures of nested maps and vectors.
9#[derive(Clone)]
10pub enum NestedValue {
11    /// The default value, which actually does not hold any value and it is used to indicate that
12    /// the value should be populated with the default value. It contains an optional string with
13    /// the originator field name.
14    Default(Option<String>),
15
16    /// A boolean value.
17    Bool(bool),
18
19    /// A string value.
20    String(String),
21
22    /// Floating point 32-bit value.
23    F32(f32),
24
25    /// Floating point 64-bit value.
26    F64(f64),
27
28    /// Signed 16-bit integer value.
29    I16(i16),
30
31    /// Signed 32-bit integer value.
32    I32(i32),
33
34    /// Signed 64-bit integer value.
35    I64(i64),
36
37    /// Unsigned 8-bit integer value.
38    U8(u8),
39
40    /// Unsigned 16-bit integer value used for bf16 and f16 serialization
41    U16(u16),
42
43    /// Unsigned 64-bit integer value.
44    U64(u64),
45
46    /// A map of nested values (typically used for structs)
47    Map(HashMap<String, NestedValue>),
48
49    /// A vector of nested values (typically used for vector of structs or numbers)
50    Vec(Vec<NestedValue>),
51
52    /// A vector of 8-bit unsigned integer values.
53    U8s(Vec<u8>),
54
55    /// A vector of 16-bit unsigned integer values.
56    U16s(Vec<u16>),
57
58    /// A vector of 32-bit floating point values.
59    F32s(Vec<f32>),
60
61    /// A value that could not be represented, holding the name of its type in the source.
62    /// Deserializing it into anything is an error; it can only be ignored.
63    Unsupported(String),
64}
65
66impl NestedValue {
67    /// Get the nested value as a map.
68    pub fn as_map(self) -> Option<HashMap<String, NestedValue>> {
69        match self {
70            NestedValue::Map(map) => Some(map),
71            _ => None,
72        }
73    }
74
75    /// Get the nested value as a boolean.
76    pub fn as_bool(self) -> Option<bool> {
77        match self {
78            NestedValue::Bool(bool) => Some(bool),
79            _ => None,
80        }
81    }
82
83    /// Get the nested value as a string.
84    pub fn as_string(self) -> Option<String> {
85        match self {
86            NestedValue::String(string) => Some(string),
87            _ => None,
88        }
89    }
90
91    /// Get the nested value as a f32.
92    pub fn as_f32(self) -> Option<f32> {
93        match self {
94            NestedValue::F32(f32) => Some(f32),
95            NestedValue::F64(f) => f.to_f32(),
96            _ => None,
97        }
98    }
99
100    /// Get the nested value as a f64.
101    pub fn as_f64(self) -> Option<f64> {
102        match self {
103            NestedValue::F64(f64) => Some(f64),
104            NestedValue::F32(f) => f.to_f64(),
105            _ => None,
106        }
107    }
108
109    /// Get the nested value as an i16.
110    pub fn as_i16(self) -> Option<i16> {
111        match self {
112            NestedValue::I16(i16) => Some(i16),
113            NestedValue::I32(i) => i.to_i16(),
114            NestedValue::I64(i) => i.to_i16(),
115            NestedValue::U16(u) => u.to_i16(),
116            NestedValue::U64(u) => u.to_i16(),
117            _ => None,
118        }
119    }
120
121    /// Get the nested value as an i32.
122    pub fn as_i32(self) -> Option<i32> {
123        match self {
124            NestedValue::I32(i32) => Some(i32),
125            NestedValue::I16(i) => i.to_i32(),
126            NestedValue::I64(i) => i.to_i32(),
127            NestedValue::U16(u) => u.to_i32(),
128            NestedValue::U64(u) => u.to_i32(),
129            _ => None,
130        }
131    }
132
133    /// Get the nested value as an i64.
134    pub fn as_i64(self) -> Option<i64> {
135        match self {
136            NestedValue::I64(i64) => Some(i64),
137            NestedValue::I16(i) => i.to_i64(),
138            NestedValue::I32(i) => i.to_i64(),
139            NestedValue::U16(u) => u.to_i64(),
140            NestedValue::U64(u) => u.to_i64(),
141            _ => None,
142        }
143    }
144
145    /// Get the nested value as a u8.
146    pub fn as_u8(self) -> Option<u8> {
147        match self {
148            NestedValue::U8(u8) => Some(u8),
149            NestedValue::I16(i) => i.to_u8(),
150            NestedValue::I32(i) => i.to_u8(),
151            NestedValue::I64(i) => i.to_u8(),
152            NestedValue::U16(u) => u.to_u8(),
153            NestedValue::U64(u) => u.to_u8(),
154            _ => None,
155        }
156    }
157
158    /// Get the nested value as a u16.
159    pub fn as_u16(self) -> Option<u16> {
160        match self {
161            NestedValue::U16(u16) => Some(u16),
162            NestedValue::I16(i) => i.to_u16(),
163            NestedValue::I32(i) => i.to_u16(),
164            NestedValue::I64(i) => i.to_u16(),
165            NestedValue::U64(u) => u.to_u16(),
166            _ => None,
167        }
168    }
169
170    /// Get the nested value as a u64.
171    pub fn as_u64(self) -> Option<u64> {
172        match self {
173            NestedValue::U64(u64) => Some(u64),
174            NestedValue::I16(i) => i.to_u64(),
175            NestedValue::I32(i) => i.to_u64(),
176            NestedValue::I64(i) => i.to_u64(),
177            NestedValue::U16(u) => u.to_u64(),
178            _ => None,
179        }
180    }
181
182    /// Get the nested value as a vector of bytes.
183    pub fn as_bytes(self) -> Option<Vec<u8>> {
184        match self {
185            NestedValue::U8s(u) => Some(u),
186            _ => None,
187        }
188    }
189}
190
191fn write_vec_truncated<T: core::fmt::Debug>(
192    vec: &[T],
193    f: &mut core::fmt::Formatter,
194) -> fmt::Result {
195    write!(f, "Vec([")?;
196    for (i, v) in vec.iter().take(3).enumerate() {
197        if i > 0 {
198            write!(f, ", ")?;
199        }
200        write!(f, "{v:?}")?;
201    }
202    write!(f, ", ...] len={})", vec.len())
203}
204
205impl fmt::Debug for NestedValue {
206    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207        match self {
208            // Truncate values for vector
209            NestedValue::Vec(vec) if vec.len() > 3 => write_vec_truncated(vec, f),
210            NestedValue::U8s(vec) if vec.len() > 3 => write_vec_truncated(vec, f),
211            NestedValue::U16s(vec) if vec.len() > 3 => write_vec_truncated(vec, f),
212            NestedValue::F32s(vec) if vec.len() > 3 => write_vec_truncated(vec, f),
213            // Handle other variants as usual
214            NestedValue::Default(origin) => f.debug_tuple("Default").field(origin).finish(),
215            NestedValue::Bool(b) => f.debug_tuple("Bool").field(b).finish(),
216            NestedValue::String(s) => f.debug_tuple("String").field(s).finish(),
217            NestedValue::F32(val) => f.debug_tuple("F32").field(val).finish(),
218            NestedValue::F64(val) => f.debug_tuple("F64").field(val).finish(),
219            NestedValue::I16(val) => f.debug_tuple("I16").field(val).finish(),
220            NestedValue::I32(val) => f.debug_tuple("I32").field(val).finish(),
221            NestedValue::I64(val) => f.debug_tuple("I64").field(val).finish(),
222            NestedValue::U8(val) => f.debug_tuple("U8").field(val).finish(),
223            NestedValue::U16(val) => f.debug_tuple("U16").field(val).finish(),
224            NestedValue::U64(val) => f.debug_tuple("U64").field(val).finish(),
225            NestedValue::Map(map) => f.debug_map().entries(map.iter()).finish(),
226            NestedValue::Vec(vec) => f.debug_list().entries(vec.iter()).finish(),
227            NestedValue::U8s(vec) => f.debug_list().entries(vec.iter()).finish(),
228            NestedValue::U16s(vec) => f.debug_list().entries(vec.iter()).finish(),
229            NestedValue::F32s(vec) => f.debug_list().entries(vec.iter()).finish(),
230            NestedValue::Unsupported(type_name) => {
231                f.debug_tuple("Unsupported").field(type_name).finish()
232            }
233        }
234    }
235}