No need to return value for Scope::get.

This commit is contained in:
Stephen Chung 2020-04-27 11:24:58 +08:00
parent 07c5abcc02
commit 5afeba6fd1
2 changed files with 25 additions and 48 deletions

View File

@ -389,7 +389,7 @@ fn search_scope<'a>(
id: &str,
begin: Position,
) -> Result<(&'a mut Dynamic, ScopeEntryType), Box<EvalAltResult>> {
let (ScopeSource { typ, index, .. }, _) = scope
let ScopeSource { typ, index, .. } = scope
.get(id)
.ok_or_else(|| Box::new(EvalAltResult::ErrorVariableNotFound(id.into(), begin)))?;
@ -1162,28 +1162,24 @@ impl Engine {
)))
}
Some((
Some(
entry
@
ScopeSource {
typ: ScopeEntryType::Normal,
..
},
_,
)) => {
}) => {
// Avoid referencing scope which is used below as mut
let entry = ScopeSource { name, ..entry };
*scope.get_mut(entry) = rhs_val.clone();
Ok(rhs_val)
}
Some((
Some(
ScopeSource {
typ: ScopeEntryType::Constant,
..
},
_,
)) => Err(Box::new(EvalAltResult::ErrorAssignmentToConstant(
}) => Err(Box::new(EvalAltResult::ErrorAssignmentToConstant(
name.to_string(),
*op_pos,
))),

View File

@ -291,35 +291,22 @@ impl<'a> Scope<'a> {
}
/// Find an entry in the Scope, starting from the last.
pub(crate) fn get(&self, name: &str) -> Option<(EntryRef, Dynamic)> {
pub(crate) fn get(&self, name: &str) -> Option<EntryRef> {
self.0
.iter()
.enumerate()
.rev() // Always search a Scope in reverse order
.find_map(
|(
index,
Entry {
.find_map(|(index, Entry { name: key, typ, .. })| {
if name == key {
Some(EntryRef {
name: key,
typ,
value,
..
},
)| {
if name == key {
Some((
EntryRef {
name: key,
index,
typ: *typ,
},
value.clone(),
))
} else {
None
}
},
)
index,
typ: *typ,
})
} else {
None
}
})
}
/// Get the value of an entry in the Scope, starting from the last.
@ -365,21 +352,15 @@ impl<'a> Scope<'a> {
/// ```
pub fn set_value<T: Variant + Clone>(&mut self, name: &'a str, value: T) {
match self.get(name) {
Some((
EntryRef {
typ: EntryType::Constant,
..
},
_,
)) => panic!("variable {} is constant", name),
Some((
EntryRef {
index,
typ: EntryType::Normal,
..
},
_,
)) => self.0.get_mut(index).unwrap().value = Dynamic::from(value),
Some(EntryRef {
typ: EntryType::Constant,
..
}) => panic!("variable {} is constant", name),
Some(EntryRef {
index,
typ: EntryType::Normal,
..
}) => self.0.get_mut(index).unwrap().value = Dynamic::from(value),
None => self.push(name, value),
}
}