#![allow(
clippy::unnecessary_wraps,
reason = "every implementation has an overload's signature, which can fail"
)]
use super::Functions;
use super::value::Value;
use compmd_macros::library;
pub(crate) type Call = fn(&dyn Functions, &[Value]) -> Result<Value, String>;
#[library(prefix = "optional.", call = Call)]
pub(crate) enum OptionalFunction {
#[overload(fn(value: Any) -> Optional(0) = of)]
Of,
#[overload(fn() -> Optional(0) = none)]
None,
}
fn of(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
Ok(Value::optional(args.first().cloned()))
}
fn none(_: &dyn Functions, _: &[Value]) -> Result<Value, String> {
Ok(Value::optional(None))
}
fn inner(args: &[Value]) -> Option<&Value> {
match args.first() {
Some(Value::Optional(Some(value))) => Some(value),
_ => None,
}
}
pub(crate) fn has_value(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
Ok(Value::Bool(inner(args).is_some()))
}
pub(crate) fn value(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
inner(args).cloned().ok_or_else(|| {
"optional.none() has no value; use orValue() for one in its place".to_string()
})
}
pub(crate) fn or_value(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
Ok(inner(args)
.or_else(|| args.get(1))
.cloned()
.unwrap_or(Value::Null))
}
pub(crate) fn or(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
let first = args.first().filter(|_| inner(args).is_some());
Ok(first
.or_else(|| args.get(1))
.cloned()
.unwrap_or(Value::Null))
}