Nested HashMap to key value Vec

How would we convert nested HashMaps to key value Vecs?

For example:

from  -  HashMap<u8, HashMap<u8, u8>> 
to    -  <(u8, Vec<(u8, u8)>)>

from  -  HashMap<HashMap<u8, u8>, u8>
to    -  Vec<(Vec<(u8, u8)>, u8)>

from  -  HashMap<HashMap<u8, u8>, HashMap<u8, u8>>
to    -  Vec<(Vec<(u8, u8)>, Vec<(u8, u8)>)>

from  -  HashMap<u8, HashMap<u8, HashMap<u8, u8>>>
to    -  Vec<(u8, Vec<(u8, Vec<(u8, u8)>)>)>

I suspect I will have to use a declarative macro to do this. Is there anything like this in crates.io or has anyone done something like this? Any resources/ideas would be really appreciated.

Where are these nested hashmaps coming from? Especially the use of a hashmap in a key position feels very unusual, since HashMap doesn’t implement the Hash trait (though in a surprise twist, BTreeMap does implement it).

Nice find @JosephOsborn this is not a problem because HashMaps can't be keys. What a lovely wild goose chase my whole day has been.

I’m glad that helped! But I still am very curious about these values and their unusual types (:

Also, I guess it’s a lucky thing that your types were HashMaps and not BTreeMaps—I was pretty surprised to read that BTreeMap implements hash if its key and value types do, since HashMap does not.

The reason for that is because BTreeMaps are ordered, so there are no two ways to hash two maps that have the same keys and values. HashMaps can have different orders depending on how they are created, even if the key-value pairs are identical.

1 Like

I use a crate called abomonation to save and load many of my structs. I have quite a few large structs with HashMaps inside them. Unfortunately I can't use the derive macro of abomonation on structs that have HashMaps in them.

So my solution is to have a loader struct that has fields like Vec<(A, B)> instead of the HashMap<A, B> that is in the main struct. Then I can use the derive macro on the loader struct instead. And I also implement some nice conversion functions on the main struct so I don't even have to touch the loader struct in practice.

The reason I wanted to come up with an easy way to convert these HashMaps to these key value pairs is because I have three variants of nestedness (always in the values). I previously thought I had more because I do actually have some keys that are structs with HashMaps in them :slight_smile:

Project is Poker Analysis related which is the reason for the HashMaps. They index how many times someone won with some cards and such stuff.