diff --git a/src/renderer/iteration_context.rs b/src/renderer/iteration_context.rs new file mode 100644 index 0000000..d294817 --- /dev/null +++ b/src/renderer/iteration_context.rs @@ -0,0 +1,71 @@ +use crate::renderer::context_element::CompareContextElement; +use crate::renderer::context_element::ContextElement; +use crate::renderer::Loopable; +use crate::renderer::RenderError; +use crate::renderer::Renderable; +use crate::renderer::WalkError; +use crate::{parser::Filter, parser::OwnedLiteral, renderer::Walkable}; + +use std::cmp::Ordering; + +/// An injected context for $idx and $len +/// +/// Functions the same as the injected parameters contexts for +/// helpers/partials with parameters but this has no need for storing +/// breadcrumbs since its simply storing two integers. +#[derive(Debug, Clone)] +pub struct IterationContext { + idx: OwnedLiteral, + len: OwnedLiteral, +} + +impl IterationContext { + pub fn new(idx: u64, len: u64) -> Self { + IterationContext { + idx: OwnedLiteral::LPositiveInteger(idx), + len: OwnedLiteral::LPositiveInteger(len), + } + } +} + +impl ContextElement for IterationContext {} + +impl Renderable for IterationContext { + fn render(&self, _filters: &Vec) -> Result { + // TODO: Would this even ever be called? Won't matter, but I'd + // like to know. Since it is injected 1 above the current + // context, we wouldn't be able to access it with `{.}`. + Ok("[object Object]".to_owned()) + } +} + +impl Loopable for IterationContext { + fn get_loop_elements(&self) -> Vec<&dyn ContextElement> { + // TODO: Would this even ever be called? Won't matter, but I'd + // like to know. Since it is injected 1 above the current + // context, we wouldn't be able to access it with `{.}`. + vec![self] + } +} + +impl Walkable for IterationContext { + fn walk(&self, segment: &str) -> Result<&dyn ContextElement, WalkError> { + match segment { + "$idx" => Ok(&self.idx), + "$len" => Ok(&self.len), + _ => Err(WalkError::CantWalk), + } + } +} + +impl CompareContextElement for IterationContext { + fn equals(&self, other: &dyn ContextElement) -> bool { + // TODO: Does this ever happen? perhaps I should have a panic here. + false + } + + fn partial_compare(&self, other: &dyn ContextElement) -> Option { + // TODO: Does this ever happen? perhaps I should have a panic here. + None + } +} diff --git a/src/renderer/mod.rs b/src/renderer/mod.rs index 45dbdfd..3878e18 100644 --- a/src/renderer/mod.rs +++ b/src/renderer/mod.rs @@ -3,6 +3,7 @@ mod context_element; mod errors; mod inline_partial_tree; +mod iteration_context; mod parameters_context; mod renderer; mod walking;