use std::collections::{BTreeMap, btree_map::Entry};
use crate::{json, schema::Integrity};
use super::{Caveat, Element, Error, Failure, Group, Rejected, Set, Source, Verdict, Warning};
pub(crate) trait Gather<W: Warning> {
#[track_caller]
fn insert_lazy(&mut self, elem_id: json::ElemId, warning: W, element: &dyn Fn() -> Element);
#[track_caller]
fn insert(&mut self, element: &json::Element<'_>, warning: W) {
self.insert_lazy(element.id(), warning, &|| Element::from_json(element));
}
#[track_caller]
fn deescalate(&mut self, error: Error<W>) {
let Error { warning, element } = error;
self.insert_lazy(element.id, warning, &|| element.clone());
}
}
impl<W: Warning> dyn Gather<W> + '_ {
#[expect(
clippy::unused_self,
reason = "the receiver only supplies the warning type"
)]
pub(crate) fn ok_or_reject<'a, T>(&self, integrity: &'a Integrity<T>) -> Result<&'a T, Error<W>>
where
W: From<Rejected>,
{
match integrity {
Integrity::Ok(value) => Ok(value),
Integrity::Missing(element) | Integrity::Err(element) => Err(Error {
warning: Rejected.into(),
element: element.clone(),
}),
}
}
}
#[derive(Debug)]
pub(crate) struct Gatherer<W: Warning>(BTreeMap<json::ElemId, Group<W>>);
impl<W: Warning> Gatherer<W> {
pub(crate) fn new() -> Self {
Self(BTreeMap::new())
}
pub(crate) fn into_verdict<T>(self, outcome: Result<T, Error<W>>) -> Verdict<T, W> {
let Self(warnings) = self;
match outcome {
Ok(value) => Ok(Caveat::new(value, Set(warnings))),
Err(error) => Err(Failure {
error: Box::new(error),
warnings: Set(warnings),
}),
}
}
pub(crate) fn into_set(self) -> Set<W> {
let Self(warnings) = self;
Set(warnings)
}
}
impl<W: Warning> Gather<W> for Gatherer<W> {
#[track_caller]
fn insert_lazy(&mut self, elem_id: json::ElemId, warning: W, element: &dyn Fn() -> Element) {
match self.0.entry(elem_id) {
Entry::Vacant(entry) => {
entry.insert_entry(Group {
element: element(),
warnings: vec![Source::new(warning)],
});
}
Entry::Occupied(mut entry) => {
entry.get_mut().warnings.push(Source::new(warning));
}
}
}
}
pub(crate) struct Converting<'p, WA: Warning>(&'p mut dyn Gather<WA>);
impl<'p, WA: Warning> Converting<'p, WA> {
pub(crate) fn new(parent: &'p mut dyn Gather<WA>) -> Self {
Self(parent)
}
}
impl<W, WA> Gather<W> for Converting<'_, WA>
where
W: Warning + Into<WA>,
WA: Warning,
{
#[track_caller]
fn insert_lazy(&mut self, elem_id: json::ElemId, warning: W, element: &dyn Fn() -> Element) {
self.0.insert_lazy(elem_id, warning.into(), element);
}
}