1#[doc(hidden)]
2#[derive(Clone)]
3pub enum Key<'a> {
4 Str(&'a str),
5 Slice(&'a [&'a str]),
6 Pair(Box<Key<'a>>, Box<Key<'a>>),
7}
8
9impl<'a> Key<'a> {
10 fn dig<I: Iterator<Item = &'a str>>(
11 path: I,
12 mut value: &serde_json::Value,
13 ) -> Option<&serde_json::Value> {
14 for part in path {
15 let value_opt = match value {
16 serde_json::Value::Object(ref map) => map.get(part),
17 serde_json::Value::Array(ref arr) => {
18 part.parse::<usize>().ok().and_then(|i| arr.get(i))
19 }
20 _ => None,
21 };
22 value = match value_opt {
23 Some(value) => value,
24 None => {
25 return None;
26 }
27 }
28 }
29 Some(value)
30 }
31
32 fn iter(&self) -> Box<dyn Iterator<Item = &'a str> + 'a> {
33 match self {
34 Key::Str(s) => Box::new(s.split('.')),
35 Key::Slice(s) => Box::new(s.into_iter().map(|x| *x)),
36 Key::Pair(a, b) => Box::new(a.iter().chain(b.iter())),
37 }
38 }
39
40 pub(crate) fn chain<I: Into<Self>>(self, other: I) -> Self {
41 Key::Pair(Box::new(self), Box::new(other.into()))
42 }
43
44 pub(crate) fn find(&'a self, value: &'a serde_json::Value) -> Option<&'a serde_json::Value> {
45 Self::dig(self.iter(), value)
46 }
47
48 pub(crate) fn to_string(&self) -> String {
49 self.iter().collect::<Vec<_>>().join(".")
50 }
51}
52
53impl<'a> From<&'a str> for Key<'a> {
54 fn from(t: &'a str) -> Self {
55 Key::Str(t)
56 }
57}
58
59impl<'a> From<&'a [&'a str]> for Key<'a> {
60 fn from(t: &'a [&'a str]) -> Self {
61 Key::Slice(t)
62 }
63}
64
65impl<'a> From<&'a [&'a str; 1]> for Key<'a> {
66 fn from(t: &'a [&'a str; 1]) -> Self {
67 Key::Slice(t)
68 }
69}
70
71impl<'a> From<&'a [&'a str; 2]> for Key<'a> {
72 fn from(t: &'a [&'a str; 2]) -> Self {
73 Key::Slice(t)
74 }
75}
76
77impl<'a> From<&'a [&'a str; 3]> for Key<'a> {
78 fn from(t: &'a [&'a str; 3]) -> Self {
79 Key::Slice(t)
80 }
81}
82
83impl<'a> From<&'a [&'a str; 4]> for Key<'a> {
84 fn from(t: &'a [&'a str; 4]) -> Self {
85 Key::Slice(t)
86 }
87}
88
89impl<'a> From<&'a [&'a str; 5]> for Key<'a> {
90 fn from(t: &'a [&'a str; 5]) -> Self {
91 Key::Slice(t)
92 }
93}
94
95impl<'a> From<&'a [&'a str; 6]> for Key<'a> {
96 fn from(t: &'a [&'a str; 6]) -> Self {
97 Key::Slice(t)
98 }
99}
100
101impl<'a> From<&'a [&'a str; 7]> for Key<'a> {
102 fn from(t: &'a [&'a str; 7]) -> Self {
103 Key::Slice(t)
104 }
105}
106
107impl<'a> From<&'a [&'a str; 8]> for Key<'a> {
108 fn from(t: &'a [&'a str; 8]) -> Self {
109 Key::Slice(t)
110 }
111}
112
113impl<'a> From<&'a [&'a str; 9]> for Key<'a> {
114 fn from(t: &'a [&'a str; 9]) -> Self {
115 Key::Slice(t)
116 }
117}
118
119impl<'a> From<&'a [&'a str; 10]> for Key<'a> {
120 fn from(t: &'a [&'a str; 10]) -> Self {
121 Key::Slice(t)
122 }
123}
124
125impl<'a> From<&'a [&'a str; 11]> for Key<'a> {
126 fn from(t: &'a [&'a str; 11]) -> Self {
127 Key::Slice(t)
128 }
129}
130
131impl<'a> From<&'a [&'a str; 12]> for Key<'a> {
132 fn from(t: &'a [&'a str; 12]) -> Self {
133 Key::Slice(t)
134 }
135}