use khive_types::{Entity, EntityAlias};
use serde::{Deserialize, Deserializer, Serialize};
use crate::strict::StrictEntity;
#[derive(Clone, Debug, Serialize)]
pub struct EntityRecord {
#[serde(flatten)]
pub entity: Entity,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub keys: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub aliases: Vec<EntityAlias>,
}
impl EntityRecord {
pub fn new(entity: Entity) -> Self {
Self {
entity,
keys: Vec::new(),
aliases: Vec::new(),
}
}
pub fn same_names(&self, other: &Self) -> bool {
same_set(&self.keys, &other.keys) && same_set(&self.aliases, &other.aliases)
}
}
impl From<Entity> for EntityRecord {
fn from(entity: Entity) -> Self {
Self::new(entity)
}
}
impl<'de> Deserialize<'de> for EntityRecord {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
StrictEntity::deserialize(deserializer)?
.try_into()
.map_err(serde::de::Error::custom)
}
}
pub(crate) fn same_set<T: Ord + Clone>(first: &[T], second: &[T]) -> bool {
if first.len() != second.len() {
return false;
}
let mut first = first.to_vec();
let mut second = second.to_vec();
first.sort();
second.sort();
first == second
}
pub(crate) fn repeated<'a>(names: impl IntoIterator<Item = &'a str>) -> Option<&'a str> {
let mut seen = std::collections::BTreeSet::new();
names.into_iter().find(|name| !seen.insert(*name))
}