aboutsummaryrefslogtreecommitdiff
path: root/src/primitive/variant.rs
diff options
context:
space:
mode:
authorMax Audron <audron@cocaine.farm>2021-07-21 18:29:26 +0200
committerMax Audron <audron@cocaine.farm>2021-07-21 18:29:26 +0200
commit50fcc8c3fff6a8348ce5df866ac33d9ccad42945 (patch)
tree0be9db49cf9377d717e48c20d63277a0590a39d3 /src/primitive/variant.rs
parentchange IRC MessageType to be a bitflag instead of enum (diff)
implement the Network trait generically for all inner Variant Types
Diffstat (limited to '')
-rw-r--r--src/primitive/variant.rs67
1 files changed, 66 insertions, 1 deletions
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<String> for Variant {
}
}
+/// Implements the Network trait genericly for everything that
+/// can be a VariantList / Vec<T>
+impl<T> crate::message::Network for Vec<T>
+where
+ T: std::convert::TryFrom<Variant> + Into<Variant> + 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<T>
+impl<T, S> crate::message::Network for HashMap<T, S>
+where
+ T: std::convert::TryFrom<Variant> + Into<Variant> + Clone + std::hash::Hash + std::cmp::Eq,
+ S: std::convert::TryFrom<Variant> + Into<Variant> + 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<Vec<u8>, Error> {
let unknown: u8 = 0x00;