Skip to content

Commit

Permalink
Add Context::get_value_cow()
Browse files Browse the repository at this point in the history
  • Loading branch information
mtopolnik committed Apr 4, 2022
1 parent c514410 commit 24df24e
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
7 changes: 6 additions & 1 deletion src/context/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
//! This crate implements two basic variants, the `EmptyContext`, that returns `None` for each identifier and cannot be manipulated, and the `HashMapContext`, that stores its mappings in hash maps.
//! The HashMapContext is type-safe and returns an error if the user tries to assign a value of a different type than before to an identifier.

use std::collections::HashMap;
use std::{borrow::Cow, collections::HashMap};

use crate::{
function::Function,
Expand All @@ -16,6 +16,11 @@ mod predefined;

/// An immutable context.
pub trait Context {
/// Returns the value that is linked to the given identifier.
fn get_value_cow(&self, identifier: &str) -> Option<Cow<'_, Value>> {
self.get_value(identifier).map(Cow::Borrowed)
}

/// Returns the value that is linked to the given identifier.
fn get_value(&self, identifier: &str) -> Option<&Value>;

Expand Down
4 changes: 2 additions & 2 deletions src/operator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -425,8 +425,8 @@ impl Operator {
VariableIdentifier { identifier } => {
expect_operator_argument_amount(arguments.len(), 0)?;

if let Some(value) = context.get_value(identifier).cloned() {
Ok(value)
if let Some(value) = context.get_value_cow(identifier) {
Ok(value.into_owned())
} else {
Err(EvalexprError::VariableIdentifierNotFound(
identifier.clone(),
Expand Down

0 comments on commit 24df24e

Please sign in to comment.