Skip to content

Commit

Permalink
Factor out duplicated code into Map::get implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
fore5fire committed Feb 24, 2024
1 parent 4d1ee43 commit 46eee3e
Showing 1 changed file with 14 additions and 18 deletions.
32 changes: 14 additions & 18 deletions interpreter/src/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,20 @@ impl PartialOrd for Map {
}
}

impl Map {
pub fn get(&self, key: &Key) -> Option<&Value> {
self.map.get(key).or_else(|| {
// Also check keys that are cross type comparable.
let converted = match key {
Key::Int(k) => Key::Uint(u64::try_from(*k).ok()?),
Key::Uint(k) => Key::Int(i64::try_from(*k).ok()?),
_ => return None,
};
self.map.get(&converted)
})
}
}

#[derive(Debug, Eq, PartialEq, Hash, Ord, Clone, PartialOrd)]
pub enum Key {
Int(i64),
Expand Down Expand Up @@ -477,41 +491,23 @@ impl<'a> Value {
.into()
}
(Value::Map(map), Value::String(property)) => map
.map
.get(&property.into())
.cloned()
.unwrap_or(Value::Null)
.into(),
(Value::Map(map), Value::Bool(property)) => map
.map
.get(&property.into())
.cloned()
.unwrap_or(Value::Null)
.into(),
(Value::Map(map), Value::Int(property)) => map
.map
.get(&property.into())
.cloned()
.or_else(|| {
// Check for matching unsinged int indexes too.
let Ok(index) = u64::try_from(property) else {
return None;
};
map.map.get(&index.into()).cloned()
})
.unwrap_or(Value::Null)
.into(),
(Value::Map(map), Value::UInt(property)) => map
.map
.get(&property.into())
.cloned()
.or_else(|| {
// Check for matching singed int indexes too.
let Ok(index) = i64::try_from(property) else {
return None;
};
map.map.get(&index.into()).cloned()
})
.unwrap_or(Value::Null)
.into(),
_ => unimplemented!(),
Expand Down

0 comments on commit 46eee3e

Please sign in to comment.