Skip to content

Commit

Permalink
Make ContextProvider return Cows
Browse files Browse the repository at this point in the history
This allows implementors to return owned values.
  • Loading branch information
fabianfreyer committed May 13, 2023
1 parent 71eeed2 commit 249b45d
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 9 deletions.
1 change: 1 addition & 0 deletions src/builtins/filters/array.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::borrow::Cow;
/// Filters operating on array
use std::collections::HashMap;

Expand Down
13 changes: 7 additions & 6 deletions src/context.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use std::collections::BTreeMap;
use std::io::Write;
use std::{borrow::Cow, collections::BTreeMap};

use serde::ser::Serialize;
use serde_json::value::{to_value, Map, Value};

use crate::errors::{Error, Result as TeraResult};
use crate::renderer::stack_frame::value_by_pointer;

/// The interface trait of a Context towards Tera
///
Expand All @@ -27,13 +28,13 @@ pub trait ContextProvider {
) -> TeraResult<()>;

/// Return a value for a given key.
fn find_value(&self, key: &str) -> Option<&Value>;
fn find_value(&self, key: &str) -> Option<Cow<Value>>;

/// Return a value given a dotted pointer path.
fn find_value_by_dotted_pointer(&self, pointer: &str) -> Option<&Value> {
fn find_value_by_dotted_pointer(&self, pointer: &str) -> Option<Cow<Value>> {
let root = pointer.split('.').next().unwrap().replace("~1", "/").replace("~0", "~");
let rest = &pointer[root.len() + 1..];
self.find_value(&root).and_then(|val| dotted_pointer(val, rest))
self.find_value(&root).and_then(|val| value_by_pointer(rest, &val))
}

/// Convert the context into JSON.
Expand All @@ -49,8 +50,8 @@ impl ContextProvider for Context {
self.try_insert(key, val)
}

fn find_value(&self, key: &str) -> Option<&Value> {
self.get(key)
fn find_value(&self, key: &str) -> Option<Cow<Value>> {
self.get(key).map(Cow::Borrowed)
}

fn into_json(self) -> Value {
Expand Down
4 changes: 2 additions & 2 deletions src/renderer/call_stack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,9 @@ where

// Not in stack frame, look in user supplied context
if key.contains('.') {
return self.context.find_value_by_dotted_pointer(key).map(Cow::Borrowed);
return self.context.find_value_by_dotted_pointer(key);
} else if let Some(value) = self.context.find_value(key) {
return Some(Cow::Borrowed(value));
return Some(value);
}

None
Expand Down
2 changes: 1 addition & 1 deletion src/renderer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ mod call_stack;
mod for_loop;
mod macros;
mod processor;
mod stack_frame;
pub(crate) mod stack_frame;

use std::io::Write;

Expand Down

0 comments on commit 249b45d

Please sign in to comment.