Skip to content

Commit fbea522

Browse files
committed
Implemented From/To Variant for HashMap
1 parent f274dd9 commit fbea522

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

gdnative-core/src/core_types/variant.rs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
use crate::*;
22
use std::borrow::Cow;
3+
use std::collections::HashMap;
34
use std::default::Default;
45
use std::fmt;
6+
use std::hash::Hash;
57
use std::mem::{forget, transmute};
68
use std::ptr;
79

@@ -1602,6 +1604,37 @@ impl<T: FromVariant> FromVariant for Vec<T> {
16021604
}
16031605
}
16041606

1607+
impl<K: ToVariant + Hash + ToVariantEq, V: ToVariant> ToVariant for HashMap<K, V> {
1608+
#[inline]
1609+
fn to_variant(&self) -> Variant {
1610+
let dict = Dictionary::new();
1611+
for (key, value) in self {
1612+
dict.insert(key, value);
1613+
}
1614+
dict.owned_to_variant()
1615+
}
1616+
}
1617+
1618+
impl<K: FromVariant + Hash + Eq, V: FromVariant> FromVariant for HashMap<K, V> {
1619+
#[inline]
1620+
fn from_variant(variant: &Variant) -> Result<Self, FromVariantError> {
1621+
let dictionary = Dictionary::from_variant(variant)?;
1622+
let len: usize = dictionary
1623+
.len()
1624+
.try_into()
1625+
.expect("Dictionary length should fit in usize");
1626+
let mut hash_map = HashMap::with_capacity(len);
1627+
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+
);
1633+
}
1634+
Ok(hash_map)
1635+
}
1636+
}
1637+
16051638
macro_rules! tuple_length {
16061639
() => { 0usize };
16071640
($_x:ident, $($xs:ident,)*) => {
@@ -1774,6 +1807,16 @@ godot_test!(
17741807
assert_eq!(Some(&f64::to_variant(&54.0)), vec_maybe[2].as_ref().err());
17751808
}
17761809

1810+
test_variant_hash_map {
1811+
let original_hash_map = HashMap::from([
1812+
("Foo".to_string(), 4u32),
1813+
("Bar".to_string(), 2u32)
1814+
]);
1815+
let variant = original_hash_map.to_variant();
1816+
let check_hash_map = variant.try_to::<HashMap<String, u32>>().expect("should be hash map");
1817+
assert_eq!(original_hash_map, check_hash_map);
1818+
}
1819+
17771820
test_variant_tuple {
17781821
let variant = (42i64, 54i64).to_variant();
17791822
let arr = variant.try_to::<VariantArray>().expect("should be array");

test/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ pub extern "C" fn run_tests(
4040

4141
status &= gdnative::core_types::test_variant_option();
4242
status &= gdnative::core_types::test_variant_result();
43+
status &= gdnative::core_types::test_variant_hash_map();
4344
status &= gdnative::core_types::test_to_variant_iter();
4445
status &= gdnative::core_types::test_variant_tuple();
4546
status &= gdnative::core_types::test_variant_dispatch();

0 commit comments

Comments
 (0)