Skip to content

Commit

Permalink
feat(codec): improve KeyValuePairs ergonomics (#515)
Browse files Browse the repository at this point in the history
  • Loading branch information
scarmuega authored Oct 1, 2024
1 parent 615e2d4 commit 80d121d
Showing 1 changed file with 60 additions and 1 deletion.
61 changes: 60 additions & 1 deletion pallas-codec/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -64,6 +64,16 @@ where
}
}

impl<K, V> FromIterator<(K, V)> for KeyValuePairs<K, V>
where
K: Clone,
V: Clone,
{
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
KeyValuePairs::Def(Vec::from_iter(iter))
}
}

impl<K, V> From<KeyValuePairs<K, V>> for Vec<(K, V)>
where
K: Clone,
Expand All @@ -87,6 +97,28 @@ where
}
}

impl<K, V> From<KeyValuePairs<K, V>> for HashMap<K, V>
where
K: Clone + Eq + std::hash::Hash,
V: Clone,
{
fn from(other: KeyValuePairs<K, V>) -> Self {
match other {
KeyValuePairs::Def(x) => x.into_iter().collect(),
KeyValuePairs::Indef(x) => x.into_iter().collect(),
}
}
}
impl<K, V> From<HashMap<K, V>> for KeyValuePairs<K, V>
where
K: Clone,
V: Clone,
{
fn from(other: HashMap<K, V>) -> Self {
KeyValuePairs::Def(other.into_iter().collect())
}
}

impl<K, V> Deref for KeyValuePairs<K, V>
where
K: Clone,
Expand Down Expand Up @@ -230,6 +262,33 @@ where
}
}

impl<K, V> TryFrom<KeyValuePairs<K, V>> for NonEmptyKeyValuePairs<K, V>
where
K: Clone,
V: Clone,
{
type Error = String;

fn try_from(value: KeyValuePairs<K, V>) -> Result<Self, Self::Error> {
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<K, V> Deref for NonEmptyKeyValuePairs<K, V>
where
K: Clone,
Expand Down

0 comments on commit 80d121d

Please sign in to comment.