Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support indexing maps with any valid key type #36

Merged
merged 4 commits into from
Feb 26, 2024
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 45 additions & 3 deletions interpreter/src/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use core::ops;
use serde::Serialize;
use std::cmp::Ordering;
use std::collections::HashMap;
use std::convert::{Infallible, TryInto};
use std::convert::{Infallible, TryFrom, TryInto};
use std::fmt::{Display, Formatter};
use std::rc::Rc;
use std::sync::Arc;
Expand All @@ -25,6 +25,22 @@ impl PartialOrd for Map {
}
}

impl Map {
/// Returns a reference to the value corresponding to the key. Implicitly converts between int
/// and uint keys.
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,7 +493,21 @@ 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
.get(&property.into())
.cloned()
.unwrap_or(Value::Null)
.into(),
(Value::Map(map), Value::Int(property)) => map
.get(&property.into())
.cloned()
.unwrap_or(Value::Null)
.into(),
(Value::Map(map), Value::UInt(property)) => map
.get(&property.into())
.cloned()
.unwrap_or(Value::Null)
Expand Down Expand Up @@ -696,7 +726,7 @@ impl ops::Rem<Value> for Value {

#[cfg(test)]
mod tests {
use crate::{Context, Program};
use crate::{objects::Key, Context, Program};
use std::collections::HashMap;

#[test]
Expand All @@ -710,4 +740,16 @@ mod tests {
let value = program.execute(&context).unwrap();
assert_eq!(value, "application/json".into());
}

#[test]
fn test_numeric_map_access() {
let mut context = Context::default();
let mut numbers = HashMap::new();
numbers.insert(Key::Uint(1), "one".to_string());
context.add_variable_from_value("numbers", numbers);

let program = Program::compile("numbers[1]").unwrap();
let value = program.execute(&context).unwrap();
assert_eq!(value, "one".into());
}
}