Skip to main content

jaq_core/
native.rs

1//! Native filter construction tools.
2
3use crate::box_iter::box_once;
4use crate::{Bind, Cv, DataT, Exn, Native, PathsPtr, RunPtr, ValR, ValXs};
5use alloc::boxed::Box;
6
7/// Name, arguments, and implementation of a filter.
8pub type Filter<F> = (&'static str, Box<[Bind]>, F);
9
10/// Native filter over a [`crate::DataT`].
11pub type Fun<D> = Filter<Native<D>>;
12
13/// Convert a filter with a run pointer to a native filter.
14pub fn run<D: DataT>((name, arity, run): Filter<RunPtr<D>>) -> Fun<D> {
15    (name, arity, Native::new(run))
16}
17
18pub(crate) type RunPathsPtr<D> = (RunPtr<D>, PathsPtr<D>);
19
20/// Convert a filter with a run and a paths pointer to a native filter.
21pub(crate) fn paths<D: DataT>((name, arity, (run, paths)): Filter<RunPathsPtr<D>>) -> Fun<D> {
22    (name, arity, Native::new(run).with_paths(paths))
23}
24
25/// Creates `n` variable arguments.
26pub fn v(n: usize) -> Box<[Bind]> {
27    core::iter::repeat(Bind::Var(())).take(n).collect()
28}
29
30/// Box Once and Map Errors to exceptions.
31pub fn bome<'a, V: 'a>(r: ValR<V>) -> ValXs<'a, V> {
32    box_once(r.map_err(Exn::from))
33}
34
35/// Create a filter that takes a single variable argument and whose output is given by
36/// the function `f` that takes the input value and the value of the variable.
37pub fn unary<'a, D: DataT>(
38    mut cv: Cv<'a, D>,
39    f: impl Fn(D::V<'a>, D::V<'a>) -> ValR<D::V<'a>> + 'a,
40) -> ValXs<'a, D::V<'a>> {
41    bome(f(cv.1, cv.0.pop_var()))
42}