1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use std::collections::HashMap;
use std::convert::{TryFrom, TryInto};
use std::hash::Hash;

use failure::Error;

use crate::bolt::value::Map;
use crate::error::ValueError;
use crate::Value;

// Have to use Value for the HashMap values since Value does not impl TryFrom<Value, Error = failure::Error>
// and we need to support HashMaps with Value values (see Node's properties field)
impl<K> TryInto<HashMap<K, Value>> for Map
where
    K: Hash + Eq + TryFrom<Value, Error = Error>,
{
    type Error = Error;

    fn try_into(self) -> Result<HashMap<K, Value>, Self::Error> {
        let mut map = HashMap::with_capacity(self.value.len());
        for (k, v) in self.value {
            map.insert(K::try_from(k)?, v);
        }
        Ok(map)
    }
}

impl<K> TryInto<HashMap<K, Value>> for Value
where
    K: Hash + Eq + TryFrom<Value, Error = Error>,
{
    type Error = Error;

    fn try_into(self) -> Result<HashMap<K, Value>, Self::Error> {
        match self {
            Value::Map(map) => Ok(map.try_into()?),
            _ => Err(ValueError::InvalidConversion(self).into()),
        }
    }
}