From 50fcc8c3fff6a8348ce5df866ac33d9ccad42945 Mon Sep 17 00:00:00 2001 From: Max Audron Date: Wed, 21 Jul 2021 18:29:26 +0200 Subject: implement the Network trait generically for all inner Variant Types --- src/primitive/variant.rs | 67 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) (limited to 'src/primitive') diff --git a/src/primitive/variant.rs b/src/primitive/variant.rs index efe69b8..d49f0dc 100644 --- a/src/primitive/variant.rs +++ b/src/primitive/variant.rs @@ -1,7 +1,8 @@ -use std::vec::Vec; +use std::{collections::HashMap, vec::Vec}; use failure::Error; +use itertools::Itertools; use log::{error, trace}; use crate::error::ProtocolError; @@ -76,6 +77,70 @@ impl From for Variant { } } +/// Implements the Network trait genericly for everything that +/// can be a VariantList / Vec +impl crate::message::Network for Vec +where + T: std::convert::TryFrom + Into + Clone, +{ + type Item = super::VariantList; + + fn to_network(&self) -> Self::Item { + self.iter().map(|i| (*i).clone().into()).collect() + } + + fn from_network(input: &mut Self::Item) -> Self { + input + .iter() + .map(|i| match T::try_from(i.clone()) { + Ok(it) => it, + // TODO handle error + _ => unreachable!(), + }) + .collect() + } +} + +/// Implements the Network trait genericly for everything that +/// can be a VariantList / Vec +impl crate::message::Network for HashMap +where + T: std::convert::TryFrom + Into + Clone + std::hash::Hash + std::cmp::Eq, + S: std::convert::TryFrom + Into + Clone + std::hash::Hash + std::cmp::Eq, +{ + type Item = super::VariantList; + + fn to_network(&self) -> Self::Item { + let mut res = Vec::with_capacity(self.len() * 2); + + self.iter().for_each(|(k, v)| { + res.push((*k).clone().into()); + res.push((*v).clone().into()); + }); + + return res; + } + + fn from_network(input: &mut Self::Item) -> Self { + let mut res = HashMap::with_capacity(input.len() / 2); + + input.iter().tuples().for_each(|(k, v)| { + res.insert( + match T::try_from(k.clone()) { + Ok(it) => it, + _ => unreachable!(), + }, + match S::try_from(v.clone()) { + Ok(it) => it, + _ => unreachable!(), + }, + ); + }); + + return res; + } +} + impl Serialize for Variant { fn serialize(&self) -> Result, Error> { let unknown: u8 = 0x00; -- cgit v1.2.3