1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
//! Provides the [Dig] trait for recursively digging through
//! a recursive data structure using a JSON-path-like selector
//! syntax.
//!
//! Also provides implementations for common types like [`serde_json::Value`].
//!
//! [`serde_json::Value`]: https://docs.serde.rs/serde_json/value/enum.Value.html
//!
//! # Features
//!
//! Provides the following features:
//!
//! - `serde_json`: Include a `Dig` implementation for `serde_json::Value`

#[cfg(feature = "serde_json")]
use serde_json::Value;

/// Used to "dig through" recursive data structures to extract
/// named values using a selector string.  Selectors are sequential
/// names separated by an ASCII '.' character, optionally prefixed
/// with a '$' root segment.
///
#[cfg_attr(
    feature = "serde_json",
    doc = r##"
# Examples

When the `serde_json` feature is enabled, [`Value`] implements `Dig`:

```
# use digger::Dig;
# use serde_json::{json, Value};
let value = json!({
    "foo": {
        "bar": {
            "baz": "hello there"
        }
    }
});

let expected = Value::String(String::from("hello there"));

assert_eq!(value.dig("foo.bar.baz"), Some(&expected));
```

[`Value`]: https://docs.serde.rs/serde_json/value/enum.Value.html
"##
)]
pub trait Dig {
    /// Retrieves a datum identified by the given name segment,
    /// or none.
    fn value_for_name(&self, name: &str) -> Option<&Self>;

    /// Fetches the data within [self] identified by the given
    /// `selector`.
    ///
    /// Selector strings have a lightweight syntax resembling basic
    /// JSON-Path selectors - chains of name segments, separated by
    /// ASCII period characters (`.`).  As in JSON Path, selectors
    /// can be absolute (i.e. prefixed with a sigil, like `$.`) or
    /// relative.
    ///
    /// Returns an optional result, containing a reference to the named
    /// data if found, and none if not.
    fn dig(&self, selector: impl AsRef<str>) -> Option<&Self> {
        selector
            .as_ref()
            .split('.')
            .skip_while(|&s| s == "$")
            .filter(|&s| !s.is_empty())
            .fold(Some(self), |res, name| match res {
                Some(d) => d.value_for_name(name),
                None => None,
            })
    }
}

#[cfg(feature = "serde_json")]
impl Dig for Value {
    fn value_for_name(&self, name: &str) -> Option<&Self> {
        match self {
            Value::Object(o) => o.get(name),
            _ => None,
        }
    }
}

#[cfg(test)]
#[cfg(feature = "serde_json")]
mod json_tests {
    use serde_json::{json, Value};

    use super::Dig;

    #[test]
    fn not_found_at_end() {
        let value = json!({
            "foo": {
                "bar": {
                    "baz": true
                }
            }
        });

        let result = value.dig("foo.bar.quux");

        assert_eq!(None, result);
    }

    #[test]
    fn not_found_at_start() {
        let value = json!({
            "foo": {
                "bar": {
                    "baz": true
                }
            }
        });

        let result = value.dig("rust.bar.baz");

        assert_eq!(None, result);
    }

    #[test]
    fn empty_selector_is_identity() {
        let value = json!({
            "foo": {
                "bar": {
                    "baz": true
                }
            }
        });

        let result = value.dig("");

        assert_eq!(Some(&value), result);
    }

    #[test]
    fn sigil_alone_is_identity() {
        let value = json!({
            "foo": {
                "bar": {
                    "baz": true
                }
            }
        });

        let result = value.dig("$");

        assert_eq!(Some(&value), result);
    }

    #[test]
    fn sigil_prefix_is_ignored() {
        let value = json!({
            "foo": {
                "bar": {
                    "baz": true
                }
            }
        });

        let result = value.dig("$.foo.bar.baz");
        let expected = Value::Bool(true);

        assert_eq!(Some(&expected), result);
    }
}