Skip to content

Commit

Permalink
Added the ability to create a value from a function (#121)
Browse files Browse the repository at this point in the history
  • Loading branch information
mitsuhiko committed Sep 19, 2022
1 parent df1f60a commit 94e9db1
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
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

0 comments on commit 94e9db1

Please sign in to comment.