Skip to content

Commit

Permalink
RUST-622 Add document square bracket indexing (#503)
Browse files Browse the repository at this point in the history
  • Loading branch information
jadalilleboe authored Nov 20, 2024
1 parent e0c5ca5 commit f1a08f8
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/bson.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use std::{
convert::{TryFrom, TryInto},
fmt::{self, Debug, Display, Formatter},
hash::Hash,
ops::Index,
};

use serde_json::{json, Value};
Expand Down Expand Up @@ -236,6 +237,20 @@ impl Debug for Bson {
}
}

impl Index<&str> for Bson {
type Output = Bson;

fn index(&self, index: &str) -> &Self::Output {
match *self {
Bson::Document(ref doc) => match doc.get(index) {
Some(v) => v,
None => &Bson::Null,
},
_ => &Bson::Null,
}
}
}

impl From<f32> for Bson {
fn from(a: f32) -> Bson {
Bson::Double(a.into())
Expand Down
12 changes: 12 additions & 0 deletions src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::{
fmt::{self, Debug, Display, Formatter},
io::{Read, Write},
iter::{Extend, FromIterator, IntoIterator},
ops::Index,
};

use ahash::RandomState;
Expand Down Expand Up @@ -139,6 +140,17 @@ impl Debug for Document {
}
}

impl Index<&str> for Document {
type Output = Bson;

fn index(&self, index: &str) -> &Self::Output {
match self.get(index) {
Some(v) => v,
None => &Bson::Null,
}
}
}

/// An iterator over Document entries.
pub struct IntoIter {
inner: indexmap::map::IntoIter<String, Bson>,
Expand Down
45 changes: 45 additions & 0 deletions src/tests/modules/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,3 +370,48 @@ fn test_pretty_printing() {
}"#;
assert_eq!(expected, format!("{d:#}"));
}

#[test]
fn test_indexing() {
let d = doc! {"x": 1};
let val = d["x"].as_i32().unwrap();
assert_eq!(val, 1);

let d = doc! {"x": {"y": 100}};
let val = d["x"]["y"].as_i32().unwrap();
assert_eq!(val, 100);

let d = doc! {"x" : true};
let val = d["x"].as_bool().unwrap();
assert!(val);

let d = doc! {"x": "y"};
let val = d["x"].as_str().unwrap();
assert_eq!(val, "y");

let d = doc! {"x": 1.9};
let val = d["x"].as_f64().unwrap();
assert_eq!(val, 1.9);

let d = doc! {"x": [1, 2, 3]};
let val = d["x"].as_array().unwrap();
assert_eq!(val.len(), 3);
}

#[test]
fn test_indexing_key_not_found() {
let d = doc! {"x": 1};
let val = &d["y"];
assert!(val.as_null().is_some());

let d = doc! {"x": {"y": 1}};
let val = &d["x"]["z"];
assert!(val.as_null().is_some());
}

#[test]
fn test_indexing_on_wrong_bson_type() {
let d = doc! {"x": {"y": 1}};
let val = &d["x"]["y"]["z"];
assert!(val.as_null().is_some());
}

0 comments on commit f1a08f8

Please sign in to comment.