Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
29 changes: 23 additions & 6 deletions src/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,28 +32,45 @@ use super::Value;
/// assert_eq!(data.get("a"), &Value::Null);
/// assert_eq!(data.get("a").get("b"), &Value::Null);
/// ```
pub trait Index<'v> {
pub trait Index {
/// Return None if the key is not already in the array or object.
#[doc(hidden)]
fn index_into(self, v: &'v Value<'v>) -> Option<&'v Value<'v>>;
fn index_into<'a, 'ctx>(self, v: &'a Value<'ctx>) -> Option<&'a Value<'ctx>>;
}

impl<'v> Index<'v> for usize {
impl Index for usize {
#[inline]
fn index_into(self, v: &'v Value<'v>) -> Option<&'v Value<'v>> {
fn index_into<'a, 'ctx>(self, v: &'a Value<'ctx>) -> Option<&'a Value<'ctx>> {
match v {
Value::Array(vec) => vec.get(self),
_ => None,
}
}
}

impl<'v, 'a: 'v> Index<'v> for &'a str {
impl Index for &str {
#[inline]
fn index_into(self, v: &'v Value<'v>) -> Option<&'v Value<'v>> {
fn index_into<'a, 'ctx>(self, v: &'a Value<'ctx>) -> Option<&'a Value<'ctx>> {
match v {
Value::Object(map) => map.iter().find(|(k, _v)| k == &self).map(|(_k, v)| v),
_ => None,
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn index_lifetime() {
fn get_str<'a>(v: &'a Value<'_>, k: &str) -> Option<&'a str> {
v.get(k).as_str()
}
let key = String::from("key");
let value = Value::Object(
vec![(key.as_str().into(), Value::Str("value".into()))].into()
);
assert_eq!(get_str(&value, &key), Some("value"));
}
}
2 changes: 1 addition & 1 deletion src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ impl<'ctx> Value<'ctx> {
/// assert_eq!(data.get("a").get("b"), &Value::Null);
/// ```
#[inline]
pub fn get<I: Index<'ctx>>(&'ctx self, index: I) -> &'ctx Value<'ctx> {
pub fn get<I: Index>(&self, index: I) -> &Value<'ctx> {
static NULL: Value = Value::Null;
index.index_into(self).unwrap_or(&NULL)
}
Expand Down