use alloc::{
collections::BTreeSet,
string::{String, ToString},
vec::Vec,
};
use crate::{AssignmentState, Document};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ComparedValue {
pub state: AssignmentState,
pub value: Option<String>,
pub exported: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DifferenceKind {
OnlyLeft,
OnlyRight,
State,
Value,
Export,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ComparisonEntry {
pub key: String,
pub left: Option<ComparedValue>,
pub right: Option<ComparedValue>,
pub kind: DifferenceKind,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Comparison {
differences: Vec<ComparisonEntry>,
}
impl Comparison {
#[must_use]
pub fn differences(&self) -> &[ComparisonEntry] {
&self.differences
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.differences.is_empty()
}
#[must_use]
pub fn len(&self) -> usize {
self.differences.len()
}
}
impl Document<'_> {
#[must_use]
pub fn compare<'a>(&'a self, other: &'a Document<'_>) -> Comparison {
let mut keys = Vec::new();
let mut seen = BTreeSet::new();
collect_keys(self, &mut keys, &mut seen);
collect_keys(other, &mut keys, &mut seen);
let left_index = self.lookup_index();
let right_index = other.lookup_index();
let mut differences = Vec::new();
for key in keys {
let left = if key.is_empty() {
self.get_entry(&key)
} else {
left_index.get_entry(&key)
}
.map(snapshot);
let right = if key.is_empty() {
other.get_entry(&key)
} else {
right_index.get_entry(&key)
}
.map(snapshot);
let kind = match (&left, &right) {
(None, Some(_)) => DifferenceKind::OnlyRight,
(Some(_), None) => DifferenceKind::OnlyLeft,
(Some(left), Some(right)) if left.state != right.state => DifferenceKind::State,
(Some(left), Some(right)) if left.value != right.value => DifferenceKind::Value,
(Some(left), Some(right)) if left.exported != right.exported => {
DifferenceKind::Export
}
(Some(_), Some(_)) | (None, None) => continue,
};
differences.push(ComparisonEntry {
key,
left,
right,
kind,
});
}
Comparison { differences }
}
}
fn collect_keys(document: &Document<'_>, keys: &mut Vec<String>, seen: &mut BTreeSet<String>) {
for entry in document.entries() {
if !entry.participates_in_lookup() {
continue;
}
let key = entry.key();
if !seen.contains(key) {
seen.insert(key.to_string());
keys.push(key.to_string());
}
}
}
fn snapshot(entry: crate::Entry<'_>) -> ComparedValue {
ComparedValue {
state: entry.state(),
value: entry.value().map(ToString::to_string),
exported: entry.exported(),
}
}