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
41
42
//! Functions for (de)serializing to and from BTreeMaps.
//!
//! See the crate-level documentation for more information.

use std::{
    collections::BTreeMap,
    hash::Hash,
};
use serde::{
    de::{Deserialize, Deserializer},
    ser::{Serialize, Serializer},
};
use super::Key;

/// Serialize a BTreeMap.
///
/// See the crate-level documentation for more information.
pub fn serialize<'a, S: Serializer, T: Serialize, U>(
    map: &BTreeMap<U, T>,
    serializer: S,
) -> Result<S::Ok, S::Error> {
    serializer.collect_seq(map.values())
}

/// Deserialize a BTreeMap.
///
/// See the crate-level documentation for more information.
pub fn deserialize<'a, D, T, U>(
    deserializer: D,
) -> Result<BTreeMap<U, T>, D::Error>
    where D: Deserializer<'a>,
          T: Key<'a, U> + Deserialize<'a>,
          U: Deserialize<'a> + Eq + Hash + Ord + Serialize {
    let items = Vec::<T>::deserialize(deserializer)?;
    let mut map = BTreeMap::new();

    for item in items {
        map.insert(item.key(), item);
    }

    Ok(map)
}