From 80d121d13a3a4f04fb90dd0378b81c1114d886e2 Mon Sep 17 00:00:00 2001 From: Santiago Carmuega Date: Tue, 1 Oct 2024 09:00:23 -0300 Subject: [PATCH] feat(codec): improve KeyValuePairs ergonomics (#515) --- pallas-codec/src/utils.rs | 61 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) diff --git a/pallas-codec/src/utils.rs b/pallas-codec/src/utils.rs index 841fdc7..5781b4c 100644 --- a/pallas-codec/src/utils.rs +++ b/pallas-codec/src/utils.rs @@ -4,7 +4,7 @@ use minicbor::{ Decode, Encode, }; use serde::{Deserialize, Serialize}; -use std::{fmt, hash::Hash as StdHash, ops::Deref}; +use std::{collections::HashMap, fmt, hash::Hash as StdHash, ops::Deref}; static TAG_SET: u64 = 258; @@ -64,6 +64,16 @@ where } } +impl FromIterator<(K, V)> for KeyValuePairs +where + K: Clone, + V: Clone, +{ + fn from_iter>(iter: T) -> Self { + KeyValuePairs::Def(Vec::from_iter(iter)) + } +} + impl From> for Vec<(K, V)> where K: Clone, @@ -87,6 +97,28 @@ where } } +impl From> for HashMap +where + K: Clone + Eq + std::hash::Hash, + V: Clone, +{ + fn from(other: KeyValuePairs) -> Self { + match other { + KeyValuePairs::Def(x) => x.into_iter().collect(), + KeyValuePairs::Indef(x) => x.into_iter().collect(), + } + } +} +impl From> for KeyValuePairs +where + K: Clone, + V: Clone, +{ + fn from(other: HashMap) -> Self { + KeyValuePairs::Def(other.into_iter().collect()) + } +} + impl Deref for KeyValuePairs where K: Clone, @@ -230,6 +262,33 @@ where } } +impl TryFrom> for NonEmptyKeyValuePairs +where + K: Clone, + V: Clone, +{ + type Error = String; + + fn try_from(value: KeyValuePairs) -> Result { + match value { + KeyValuePairs::Def(x) => { + if x.is_empty() { + Err("NonEmptyKeyValuePairs must contain at least one element".into()) + } else { + Ok(NonEmptyKeyValuePairs::Def(x)) + } + } + KeyValuePairs::Indef(x) => { + if x.is_empty() { + Err("NonEmptyKeyValuePairs must contain at least one element".into()) + } else { + Ok(NonEmptyKeyValuePairs::Indef(x)) + } + } + } + } +} + impl Deref for NonEmptyKeyValuePairs where K: Clone,