tek/output/src/either.rs

33 lines
1.3 KiB
Rust

use crate::*;
/// Show one item if a condition is true and another if the condition is false
pub struct Either<E, A, B>(pub PhantomData<E>, pub bool, pub A, pub B);
impl<E, A, B> Either<E, A, B> {
pub fn new (c: bool, a: A, b: B) -> Self {
Self(Default::default(), c, a, b)
}
}
impl<'a, E: Output + 'a, T: EdnViewData<'a, E>> TryFromEdn<'a, T> for Either<E, RenderBox<'a, E>, RenderBox<'a, E>> {
fn try_from_edn (state: &'a T, head: &EdnItem<&str>, tail: &'a [EdnItem<&str>]) -> Option<Self> {
use EdnItem::*;
if let (Key("either"), [condition, content, alternative]) = (head, tail) {
Some(Self::new(
state.get(condition).expect("either: no condition"),
state.get(content).expect("either: no content"),
state.get(alternative).expect("either: no alternative")
))
} else {
None
}
}
}
impl<E: Output, A: Render<E>, B: Render<E>> Content<E> for Either<E, A, B> {
fn layout (&self, to: E::Area) -> E::Area {
let Self(_, cond, a, b) = self;
if *cond { a.layout(to) } else { b.layout(to) }
}
fn render (&self, to: &mut E) {
let Self(_, cond, a, b) = self;
if *cond { a.render(to) } else { b.render(to) }
}
}