use jsonld_core::HashMap;
use parking_lot::Mutex;
use std::{hash::Hash, sync::Arc};
pub const MAX_REMOTE_CONTEXTS: usize = 64;
struct StackNode<I> {
previous: Option<Arc<StackNode<I>>>,
url: I,
}
impl<I> StackNode<I> {
fn new(previous: Option<Arc<StackNode<I>>>, url: I) -> StackNode<I> {
StackNode { previous, url }
}
fn contains(&self, url: &I) -> bool
where
I: PartialEq,
{
if self.url == *url {
true
} else {
match &self.previous {
Some(prev) => prev.contains(url),
None => false,
}
}
}
}
pub struct ProcessingStack<I> {
head: Option<Arc<StackNode<I>>>,
dereferenced: Arc<Mutex<HashMap<I, Arc<jsonld_syntax::context::Context>>>>,
}
impl<I> Clone for ProcessingStack<I> {
fn clone(&self) -> Self {
Self {
head: self.head.clone(),
dereferenced: Arc::clone(&self.dereferenced),
}
}
}
impl<I> ProcessingStack<I> {
#[must_use]
pub fn new() -> Self {
Self {
head: None,
dereferenced: Arc::new(Mutex::new(HashMap::default())),
}
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.head.is_none()
}
#[must_use]
pub fn len(&self) -> usize {
let mut len = 0;
let mut node = &self.head;
while let Some(frame) = node {
len += 1;
node = &frame.previous;
}
len
}
pub fn cycle(&self, url: &I) -> bool
where
I: PartialEq,
{
match &self.head {
Some(head) => head.contains(url),
None => false,
}
}
pub fn push(&mut self, url: I) -> bool
where
I: PartialEq,
{
if self.cycle(&url) {
false
} else {
self.enter(url);
true
}
}
pub fn enter(&mut self, url: I) {
let previous = self.head.take();
self.head = Some(Arc::new(StackNode::new(previous, url)));
}
pub fn dereferenced(&self, url: &I) -> Option<Arc<jsonld_syntax::context::Context>>
where
I: Eq + Hash,
{
self.dereferenced.lock().get(url).map(Arc::clone)
}
pub fn remember_dereferenced(&self, url: I, context: Arc<jsonld_syntax::context::Context>)
where
I: Eq + Hash,
{
self.dereferenced.lock().insert(url, context);
}
}
impl<I> Default for ProcessingStack<I> {
fn default() -> Self {
Self::new()
}
}