use std::collections::HashMap;
use derec_proto::{CommunicationInfo, CommunicationInfoKeyValue, communication_info_key_value};
pub(crate) trait CommunicationInfoExt {
fn to_map(&self) -> HashMap<String, String>;
fn from_map(map: &HashMap<String, String>) -> Self;
}
impl CommunicationInfoExt for CommunicationInfo {
fn to_map(&self) -> HashMap<String, String> {
self.communication_info_entries
.iter()
.filter_map(|e| match &e.value {
Some(communication_info_key_value::Value::StringValue(s)) => {
Some((e.key.to_owned(), s.to_owned()))
}
_ => None,
})
.collect()
}
fn from_map(map: &HashMap<String, String>) -> Self {
Self {
communication_info_entries: map
.iter()
.map(|(k, v)| CommunicationInfoKeyValue {
key: k.to_owned(),
value: Some(communication_info_key_value::Value::StringValue(
v.to_owned(),
)),
})
.collect(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use derec_proto::{CommunicationInfo, CommunicationInfoKeyValue, communication_info_key_value};
use std::collections::HashMap;
fn string_entry(key: &str, value: &str) -> CommunicationInfoKeyValue {
CommunicationInfoKeyValue {
key: key.to_owned(),
value: Some(communication_info_key_value::Value::StringValue(
value.to_owned(),
)),
}
}
#[test]
fn a_map_round_trips_through_the_proto() {
let map = HashMap::from([
("nickname".to_owned(), "Alice".to_owned()),
("avatar".to_owned(), "https://a.example/x.png".to_owned()),
]);
assert_eq!(CommunicationInfo::from_map(&map).to_map(), map);
}
#[test]
fn a_bytes_entry_is_skipped_rather_than_refused() {
let info = CommunicationInfo {
communication_info_entries: vec![
string_entry("nickname", "Alice"),
CommunicationInfoKeyValue {
key: "avatar".to_owned(),
value: Some(communication_info_key_value::Value::BytesValue(vec![
0xDE, 0xAD,
])),
},
],
};
assert_eq!(
info.to_map(),
HashMap::from([("nickname".to_owned(), "Alice".to_owned())]),
);
}
#[test]
fn an_entry_with_no_value_is_skipped() {
let info = CommunicationInfo {
communication_info_entries: vec![CommunicationInfoKeyValue {
key: "nickname".to_owned(),
value: None,
}],
};
assert!(info.to_map().is_empty());
}
#[test]
fn no_key_is_treated_as_special() {
let map = HashMap::from([("derec.replica_id".to_owned(), "7".to_owned())]);
assert_eq!(CommunicationInfo::from_map(&map).to_map(), map);
}
#[test]
fn an_empty_map_makes_an_empty_proto() {
assert!(
CommunicationInfo::from_map(&HashMap::new())
.communication_info_entries
.is_empty()
);
}
}