use std::sync::{Arc, Mutex, PoisonError};
use super::format::{Fault, Format, Reading, Refusal};
use super::limits::Limits;
use super::tree::Node;
pub(super) type Read = Result<Node, Refusal>;
#[derive(Debug, Default)]
pub(super) struct Kept(Mutex<Option<Held>>);
#[derive(Clone, Debug)]
struct Held {
limits: Limits,
reading: Reading,
read: Arc<Read>,
}
impl Held {
fn serves(&self, limits: &Limits, reading: Reading) -> bool {
self.limits == *limits
&& (self.reading == reading
|| (self.reading == Reading::Strict
&& reading == Reading::Listing
&& self.repeats_in_listing()))
}
fn repeats_in_listing(&self) -> bool {
match self.read.as_ref() {
Ok(_) => true,
Err(refusal) => matches!(
refusal.fault(),
Fault::Limit { .. } | Fault::TooLarge { .. }
),
}
}
}
impl Clone for Kept {
fn clone(&self) -> Self {
Self(Mutex::new(self.held()))
}
}
impl PartialEq for Kept {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl Eq for Kept {}
impl Kept {
fn held(&self) -> Option<Held> {
self.0
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone()
}
pub(super) fn tree(
&self,
format: &dyn Format,
text: &str,
limits: &Limits,
reading: Reading,
) -> Arc<Read> {
let mut held = self.0.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(kept) = held.as_ref()
&& kept.serves(limits, reading)
{
return Arc::clone(&kept.read);
}
let read = Arc::new(format.read(text, limits, reading));
*held = Some(Held {
limits: limits.clone(),
reading,
read: Arc::clone(&read),
});
read
}
}