Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added the ability to create a value from a function #121

Merged
merged 2 commits into from Sep 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Expand Up @@ -2,6 +2,10 @@

All notable changes to MiniJinja are documented here.

# Unreleased

- Added `Value::from_function`.

# 0.22.1

- Fixed an incorrect manifest for `minijinja-autoreload`.
Expand Down
2 changes: 1 addition & 1 deletion minijinja/src/environment.rs
Expand Up @@ -413,7 +413,7 @@ impl<'source> Environment<'source> {
Rv: FunctionResult,
Args: for<'a> FunctionArgs<'a>,
{
self.add_global(name, functions::BoxedFunction::new(f).to_value());
self.add_global(name, Value::from_function(f))
}

/// Adds a global variable.
Expand Down
13 changes: 13 additions & 0 deletions minijinja/src/value/mod.rs
Expand Up @@ -78,6 +78,7 @@ use std::sync::Arc;
use serde::ser::{Serialize, Serializer};

use crate::error::{Error, ErrorKind};
use crate::functions;
use crate::key::{Key, StaticKey};
use crate::utils::OnDrop;
use crate::value::serialize::ValueSerializer;
Expand Down Expand Up @@ -370,6 +371,18 @@ impl Value {
Value::from_rc_object(Arc::new(value))
}

/// Creates a callable value from a function.
pub fn from_function<F, Rv, Args>(f: F) -> Value
where
// the crazy bounds here exist to enable borrowing in closures
F: functions::Function<Rv, Args>
+ for<'a> functions::Function<Rv, <Args as FunctionArgs<'a>>::Output>,
Rv: FunctionResult,
Args: for<'a> FunctionArgs<'a>,
{
functions::BoxedFunction::new(f).to_value()
}

/// Returns some reference to the boxed object if it is of type `T`, or None if it isn’t.
///
/// This is basically the "reverse" of [`from_object`](Self::from_object).
Expand Down