1use byteorder::WriteBytesExt;
2use byteorder::{ByteOrder, LittleEndian};
3use std::io::Write;
4use std::{
5 collections::HashMap,
6 ops::{Deref, DerefMut},
7};
8use thiserror::Error;
9
10use crate::format::io::WriteLengthTaggedExt;
11
12pub const VARIANT_DICTIONARY_VERSION: u16 = 0x100;
13pub const VARIANT_DICTIONARY_END: u8 = 0x0;
14
15pub const U32_TYPE_ID: u8 = 0x04;
16pub const U64_TYPE_ID: u8 = 0x05;
17pub const BOOL_TYPE_ID: u8 = 0x08;
18pub const I32_TYPE_ID: u8 = 0x0c;
19pub const I64_TYPE_ID: u8 = 0x0d;
20pub const STR_TYPE_ID: u8 = 0x18;
21pub const BYTES_TYPE_ID: u8 = 0x42;
22
23#[derive(Debug, PartialEq, Eq, Clone, Default, serde::Serialize)]
25pub struct VariantDictionary(HashMap<String, VariantDictionaryValue>);
26
27impl Deref for VariantDictionary {
28 type Target = HashMap<String, VariantDictionaryValue>;
29
30 fn deref(&self) -> &Self::Target {
31 &self.0
32 }
33}
34
35impl DerefMut for VariantDictionary {
36 fn deref_mut(&mut self) -> &mut Self::Target {
37 &mut self.0
38 }
39}
40
41impl VariantDictionary {
42 pub fn new() -> Self {
44 Self(HashMap::new())
45 }
46
47 pub(crate) fn parse(buffer: &[u8]) -> Result<VariantDictionary, VariantDictionaryError> {
48 let version = buffer.get(0..2).ok_or(VariantDictionaryError::UnexpectedEof)?;
49 let version = LittleEndian::read_u16(version);
50
51 if version != VARIANT_DICTIONARY_VERSION {
52 return Err(VariantDictionaryError::InvalidVersion { version });
53 }
54
55 let mut pos = 2;
56 let mut data = HashMap::new();
57
58 while pos + 9 < buffer.len() {
59 let value_type = *buffer.get(pos).ok_or(VariantDictionaryError::UnexpectedEof)?;
60 pos += 1;
61
62 let key_length = buffer.get(pos..(pos + 4)).ok_or(VariantDictionaryError::UnexpectedEof)?;
63 let key_length = LittleEndian::read_u32(key_length) as usize;
64 pos += 4;
65
66 let key = buffer.get(pos..(pos + key_length)).ok_or(VariantDictionaryError::UnexpectedEof)?;
67 let key = String::from_utf8_lossy(key).to_string();
68 pos += key_length;
69
70 let value_length = buffer.get(pos..(pos + 4)).ok_or(VariantDictionaryError::UnexpectedEof)?;
71 let value_length = LittleEndian::read_u32(value_length) as usize;
72 pos += 4;
73
74 let value_buffer = buffer.get(pos..(pos + value_length)).ok_or(VariantDictionaryError::UnexpectedEof)?;
75 pos += value_length;
76
77 let value = match value_type {
78 U32_TYPE_ID => VariantDictionaryValue::UInt32(LittleEndian::read_u32(value_buffer)),
79 U64_TYPE_ID => VariantDictionaryValue::UInt64(LittleEndian::read_u64(value_buffer)),
80 BOOL_TYPE_ID => VariantDictionaryValue::Bool(value_buffer != [0]),
81 I32_TYPE_ID => VariantDictionaryValue::Int32(LittleEndian::read_i32(value_buffer)),
82 I64_TYPE_ID => VariantDictionaryValue::Int64(LittleEndian::read_i64(value_buffer)),
83 STR_TYPE_ID => VariantDictionaryValue::String(String::from_utf8_lossy(value_buffer).to_string()),
84 BYTES_TYPE_ID => VariantDictionaryValue::ByteArray(value_buffer.to_vec()),
85 _ => {
86 return Err(VariantDictionaryError::InvalidValueType { value_type });
87 }
88 };
89
90 data.insert(key, value);
91 }
92
93 if pos == buffer.len() || *buffer.get(pos).ok_or(VariantDictionaryError::UnexpectedEof)? != VARIANT_DICTIONARY_END {
94 return Err(VariantDictionaryError::NotTerminated);
98 }
99
100 Ok(VariantDictionary(data))
101 }
102
103 pub(crate) fn dump(&self, writer: &mut dyn Write) -> Result<(), std::io::Error> {
104 writer.write_u16::<LittleEndian>(VARIANT_DICTIONARY_VERSION)?;
105
106 for (field_name, field_value) in &self.0 {
107 match field_value {
108 VariantDictionaryValue::UInt32(value) => {
109 writer.write_u8(U32_TYPE_ID)?;
110 writer.write_with_len(field_name.as_bytes())?;
111 writer.write_u32::<LittleEndian>(4)?;
112 writer.write_u32::<LittleEndian>(*value)?;
113 }
114 VariantDictionaryValue::UInt64(value) => {
115 writer.write_u8(U64_TYPE_ID)?;
116 writer.write_with_len(field_name.as_bytes())?;
117 writer.write_u32::<LittleEndian>(8)?;
118 writer.write_u64::<LittleEndian>(*value)?;
119 }
120 VariantDictionaryValue::Bool(value) => {
121 writer.write_u8(BOOL_TYPE_ID)?;
122 writer.write_with_len(field_name.as_bytes())?;
123 writer.write_u32::<LittleEndian>(1)?;
124 writer.write_u8(if *value { 1 } else { 0 })?;
125 }
126 VariantDictionaryValue::Int32(value) => {
127 writer.write_u8(I32_TYPE_ID)?;
128 writer.write_with_len(field_name.as_bytes())?;
129 writer.write_u32::<LittleEndian>(4)?;
130 writer.write_i32::<LittleEndian>(*value)?;
131 }
132 VariantDictionaryValue::Int64(value) => {
133 writer.write_u8(I64_TYPE_ID)?;
134 writer.write_with_len(field_name.as_bytes())?;
135 writer.write_u32::<LittleEndian>(8)?;
136 writer.write_i64::<LittleEndian>(*value)?;
137 }
138 VariantDictionaryValue::String(value) => {
139 writer.write_u8(STR_TYPE_ID)?;
140 writer.write_with_len(field_name.as_bytes())?;
141 writer.write_with_len(value.as_bytes())?;
142 }
143 VariantDictionaryValue::ByteArray(value) => {
144 writer.write_u8(BYTES_TYPE_ID)?;
145 writer.write_with_len(field_name.as_bytes())?;
146 writer.write_with_len(value)?;
147 }
148 };
149 }
150
151 writer.write_u8(VARIANT_DICTIONARY_END)?;
153 Ok(())
154 }
155
156 pub fn get_typed<'a, T: 'a>(&'a self, key: &str) -> Result<&'a T, VariantDictionaryError>
159 where
160 &'a VariantDictionaryValue: Into<Option<&'a T>>,
161 {
162 let vdv = self.0.get(key).ok_or_else(|| VariantDictionaryError::MissingKey { key: key.to_owned() })?;
163
164 vdv.into().ok_or_else(|| VariantDictionaryError::Mistyped { key: key.to_owned() })
165 }
166
167 pub fn set<T>(&mut self, key: &str, value: T)
169 where
170 T: Into<VariantDictionaryValue>,
171 {
172 self.insert(key.to_string(), value.into());
173 }
174}
175
176#[derive(Debug, PartialEq, Eq, Clone, serde::Serialize)]
178#[non_exhaustive]
179pub enum VariantDictionaryValue {
180 UInt32(u32),
182
183 UInt64(u64),
185
186 Bool(bool),
188
189 Int32(i32),
191
192 Int64(i64),
194
195 String(String),
197
198 ByteArray(Vec<u8>),
200}
201
202impl From<u32> for VariantDictionaryValue {
203 fn from(v: u32) -> Self {
204 VariantDictionaryValue::UInt32(v)
205 }
206}
207
208impl From<u64> for VariantDictionaryValue {
209 fn from(v: u64) -> Self {
210 VariantDictionaryValue::UInt64(v)
211 }
212}
213
214impl From<i32> for VariantDictionaryValue {
215 fn from(v: i32) -> Self {
216 VariantDictionaryValue::Int32(v)
217 }
218}
219
220impl From<i64> for VariantDictionaryValue {
221 fn from(v: i64) -> Self {
222 VariantDictionaryValue::Int64(v)
223 }
224}
225
226impl From<bool> for VariantDictionaryValue {
227 fn from(v: bool) -> Self {
228 VariantDictionaryValue::Bool(v)
229 }
230}
231
232impl From<String> for VariantDictionaryValue {
233 fn from(v: String) -> Self {
234 VariantDictionaryValue::String(v)
235 }
236}
237
238impl From<Vec<u8>> for VariantDictionaryValue {
239 fn from(v: Vec<u8>) -> Self {
240 VariantDictionaryValue::ByteArray(v)
241 }
242}
243
244impl<'a> From<&'a VariantDictionaryValue> for Option<&'a u32> {
245 fn from(val: &'a VariantDictionaryValue) -> Self {
246 match val {
247 VariantDictionaryValue::UInt32(v) => Some(v),
248 _ => None,
249 }
250 }
251}
252
253impl<'a> From<&'a VariantDictionaryValue> for Option<&'a u64> {
254 fn from(val: &'a VariantDictionaryValue) -> Self {
255 match val {
256 VariantDictionaryValue::UInt64(v) => Some(v),
257 _ => None,
258 }
259 }
260}
261
262impl<'a> From<&'a VariantDictionaryValue> for Option<&'a bool> {
263 fn from(val: &'a VariantDictionaryValue) -> Self {
264 match val {
265 VariantDictionaryValue::Bool(v) => Some(v),
266 _ => None,
267 }
268 }
269}
270
271impl<'a> From<&'a VariantDictionaryValue> for Option<&'a i32> {
272 fn from(val: &'a VariantDictionaryValue) -> Self {
273 match val {
274 VariantDictionaryValue::Int32(v) => Some(v),
275 _ => None,
276 }
277 }
278}
279
280impl<'a> From<&'a VariantDictionaryValue> for Option<&'a i64> {
281 fn from(val: &'a VariantDictionaryValue) -> Self {
282 match val {
283 VariantDictionaryValue::Int64(v) => Some(v),
284 _ => None,
285 }
286 }
287}
288
289impl<'a> From<&'a VariantDictionaryValue> for Option<&'a String> {
290 fn from(val: &'a VariantDictionaryValue) -> Self {
291 match val {
292 VariantDictionaryValue::String(v) => Some(v),
293 _ => None,
294 }
295 }
296}
297
298impl<'a> From<&'a VariantDictionaryValue> for Option<&'a Vec<u8>> {
299 fn from(val: &'a VariantDictionaryValue) -> Self {
300 match val {
301 VariantDictionaryValue::ByteArray(v) => Some(v),
302 _ => None,
303 }
304 }
305}
306
307#[derive(Debug, Error)]
309#[non_exhaustive]
310pub enum VariantDictionaryError {
311 #[error("Invalid variant dictionary version: {}", version)]
313 InvalidVersion {
314 version: u16,
316 },
317
318 #[error("Invalid value type: {}", value_type)]
320 InvalidValueType {
321 value_type: u8,
323 },
324
325 #[error("Missing key: {}", key)]
327 MissingKey {
328 key: String,
330 },
331
332 #[error("Mistyped value: {}", key)]
334 Mistyped {
335 key: String,
337 },
338
339 #[error("VariantDictionary did not end with null byte, when it should")]
341 NotTerminated,
342
343 #[error("Unexpected end of file while parsing VariantDictionary")]
345 UnexpectedEof,
346}
347
348#[allow(clippy::unwrap_used)]
349#[cfg(test)]
350mod variant_dictionary_tests {
351 use hex_literal::hex;
352
353 use super::*;
354
355 #[test]
356 fn parsing_errors() -> Result<(), VariantDictionaryError> {
357 let res = VariantDictionary::parse("not-a-variant-dictionary".as_bytes());
358 assert!(matches!(res, Err(VariantDictionaryError::InvalidVersion { .. })));
359
360 let res = VariantDictionary::parse(&hex!("0001"));
361 assert!(matches!(res, Err(VariantDictionaryError::NotTerminated)));
362
363 let res = VariantDictionary::parse(&hex!("000100"));
364 assert!(res.is_ok());
365
366 let res = VariantDictionary::parse(&hex!("000104030000004142430400000015CD5B0700"))?;
369 assert_eq!(res.get_typed::<u32>("ABC")?, &123456789);
370
371 let res = VariantDictionary::parse(&hex!("0001AA0200000041420000000000"));
374 dbg!(&res);
375 assert!(matches!(res, Err(VariantDictionaryError::InvalidValueType { value_type: 0xAA })));
376
377 Ok(())
378 }
379
380 #[test]
381 fn variant_dictionary() {
382 let mut vd = VariantDictionary::new();
383
384 vd.set("a-u32", 42u32);
385 vd.set("a-u64", 1337u64);
386 vd.set("a-i32", -2i32);
387 vd.set("a-i64", -31337i64);
388 vd.set("a-bool", true);
389 vd.set("a-string", "Testing".to_string());
390 vd.set("a-bytes", "testing".as_bytes().to_vec());
391
392 assert!(vd.get_typed::<bool>("key-not-exist").is_err());
393
394 assert!(vd.get_typed::<u32>("a-string").is_err());
395 assert!(vd.get_typed::<u64>("a-string").is_err());
396 assert!(vd.get_typed::<i32>("a-string").is_err());
397 assert!(vd.get_typed::<i64>("a-string").is_err());
398 assert!(vd.get_typed::<bool>("a-string").is_err());
399 assert!(vd.get_typed::<String>("a-bytes").is_err());
400 assert!(vd.get_typed::<Vec<u8>>("a-string").is_err());
401
402 assert_eq!(vd.get_typed::<u32>("a-u32").unwrap(), &42u32);
403 assert_eq!(vd.get_typed::<u64>("a-u64").unwrap(), &1337u64);
404 assert_eq!(vd.get_typed::<i32>("a-i32").unwrap(), &-2i32);
405 assert_eq!(vd.get_typed::<i64>("a-i64").unwrap(), &-31337i64);
406 assert_eq!(vd.get_typed::<bool>("a-bool").unwrap(), &true);
407 assert_eq!(vd.get_typed::<String>("a-string").unwrap(), "Testing");
408 assert_eq!(vd.get_typed::<Vec<u8>>("a-bytes").unwrap(), "testing".as_bytes());
409
410 let mut vd_data = Vec::new();
411 vd.dump(&mut vd_data).unwrap();
412
413 let vd_parsed = VariantDictionary::parse(&vd_data).unwrap();
414 assert_eq!(vd_parsed, vd);
415 }
416}