sonic_rs/pointer/point.rs
1use faststr::FastStr;
2
3/// Represents a json pointer path. It can be created by [`pointer!`] macro.
4pub type JsonPointer = [PointerNode];
5
6/// Represents a node in a json pointer path.
7#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
8pub enum PointerNode {
9 Key(FastStr),
10 Index(usize),
11}
12
13/// Represents a json pointer path.
14///
15/// Used to indexing a [`Value`][`crate::Value`], [`LazyValue`][`crate::LazyValue`],
16/// [`get`][`crate::get`] or [`get_unchecked`][`crate::get_unchecked`].
17///
18/// The path can includes both keys or indexes.
19/// - keys: string-like, used to indexing an object.
20/// - indexes: usize-like, used to indexing an array.
21///
22/// # Examples
23///
24/// ```
25/// # use sonic_rs::pointer;
26/// use sonic_rs::JsonValueTrait;
27///
28/// let value: sonic_rs::Value = sonic_rs::from_str(
29/// r#"{
30/// "foo": [
31/// 0,
32/// 1,
33/// {
34/// "bar": 123
35/// }
36/// ]
37/// }"#,
38/// )
39/// .unwrap();
40/// let path = pointer!["foo", 2, "bar"];
41///
42/// let got = value.pointer(&path).unwrap();
43///
44/// assert_eq!(got, 123);
45/// ```
46#[macro_export]
47macro_rules! pointer {
48 () => (
49 ([] as [$crate::PointerNode; 0])
50 );
51 ($($x:expr),+ $(,)?) => (
52 [$($crate::PointerNode::from($x)),+]
53 );
54}
55
56#[cfg(test)]
57mod test {
58 #[test]
59 fn test_json_pointer() {
60 let pointers = pointer![];
61 println!("{pointers:?}");
62 let mut pointers = pointer![1, 2, 3, "foo", "bar"].to_vec();
63 pointers.push(123.into());
64 println!("{pointers:?}");
65 }
66}