Skip to content

Commit b005fc8

Browse files
committed
Testing invalid dictionary conversion to a HashMap
1 parent fbea522 commit b005fc8

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

gdnative-core/src/core_types/variant.rs

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1625,11 +1625,7 @@ impl<K: FromVariant + Hash + Eq, V: FromVariant> FromVariant for HashMap<K, V> {
16251625
.expect("Dictionary length should fit in usize");
16261626
let mut hash_map = HashMap::with_capacity(len);
16271627
for (key, value) in dictionary.iter() {
1628-
hash_map.insert(
1629-
K::from_variant(&key)?,
1630-
// Maybe add a custom FromVariantError variant if this fails
1631-
V::from_variant(&value)?,
1632-
);
1628+
hash_map.insert(K::from_variant(&key)?, V::from_variant(&value)?);
16331629
}
16341630
Ok(hash_map)
16351631
}
@@ -1815,6 +1811,28 @@ godot_test!(
18151811
let variant = original_hash_map.to_variant();
18161812
let check_hash_map = variant.try_to::<HashMap<String, u32>>().expect("should be hash map");
18171813
assert_eq!(original_hash_map, check_hash_map);
1814+
// Check conversion of heterogeneous dictionary key types
1815+
let non_homogenous_key_dictonary = Dictionary::new();
1816+
non_homogenous_key_dictonary.insert("Foo".to_string(), 4u32);
1817+
non_homogenous_key_dictonary.insert(7, 2u32);
1818+
assert_eq!(
1819+
non_homogenous_key_dictonary.owned_to_variant().try_to::<HashMap<String, u32>>(),
1820+
Err(FromVariantError::InvalidVariantType {
1821+
variant_type: VariantType::I64,
1822+
expected: VariantType::GodotString
1823+
}),
1824+
);
1825+
// Check conversion of heterogeneous dictionary value types
1826+
let non_homogenous_value_dictonary = Dictionary::new();
1827+
non_homogenous_value_dictonary.insert("Foo".to_string(), 4u32);
1828+
non_homogenous_value_dictonary.insert("Bar".to_string(), "Unexpected".to_string());
1829+
assert_eq!(
1830+
non_homogenous_value_dictonary.owned_to_variant().try_to::<HashMap<String, u32>>(),
1831+
Err(FromVariantError::InvalidVariantType {
1832+
variant_type: VariantType::GodotString,
1833+
expected: VariantType::I64
1834+
}),
1835+
);
18181836
}
18191837

18201838
test_variant_tuple {

0 commit comments

Comments
 (0)