1use crate::parser;
19use crate::traverse;
20use serde_value::Value;
21use std::str::FromStr;
22
23#[derive(Eq, PartialEq, PartialOrd, Debug, Clone)]
25pub struct Pointer {
26 steps: Vec<Step>,
27}
28
29#[derive(Eq, PartialEq, PartialOrd, Debug, Clone)]
31pub enum Step {
32 Name(String),
33 Index(usize),
34 NewElement,
35}
36
37pub type ParseError = parser::ParseError;
38pub type ValuePointer<'a> = traverse::ValuePointer<'a>;
39pub type ValuePointerMut<'a> = traverse::ValuePointerMut<'a>;
40
41impl Pointer {
42 pub fn push(&mut self, step: Step) -> &mut Self {
43 self.steps.push(step);
44 self
45 }
46
47 pub fn pop(&mut self) -> Option<Step> {
48 self.steps.pop()
49 }
50
51 pub fn insert(&mut self, index: usize, step: Step) {
52 self.steps.insert(index, step)
53 }
54
55 pub fn remove(&mut self, index: usize) -> Step {
56 self.steps.remove(index)
57 }
58
59 pub fn traverse<'a>(&self, val: &'a Value) -> Option<ValuePointer<'a>> {
61 traverse::traverse(val, self)
62 }
63
64 pub fn traverse_mut<'a>(&self, val: &'a mut Value) -> Option<ValuePointerMut<'a>> {
65 traverse::traverse_mut(val, self)
66 }
67
68 pub fn find<'a>(&self, val: &'a Value) -> Option<&'a Value> {
70 match self.traverse(val) {
71 Some(ValuePointer::Existing(v)) => Some(v),
72 _ => None,
73 }
74 }
75
76 pub fn find_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> {
77 match self.traverse_mut(val) {
78 Some(ValuePointerMut::Existing(v)) => Some(v),
79 _ => None,
80 }
81 }
82}
83
84impl FromStr for Pointer {
85 type Err = ParseError;
86
87 fn from_str(s: &str) -> Result<Self, Self::Err> {
88 parser::parse(s)
89 }
90}
91
92impl From<Vec<Step>> for Pointer {
93 fn from(ps: Vec<Step>) -> Self {
94 Self { steps: ps }
95 }
96}
97
98impl Into<Vec<Step>> for Pointer {
99 fn into(self) -> Vec<Step> {
100 self.steps
101 }
102}
103
104impl IntoIterator for Pointer {
105 type Item = Step;
106 type IntoIter = std::vec::IntoIter<Step>;
107
108 fn into_iter(self) -> Self::IntoIter {
109 self.steps.into_iter()
110 }
111}
112
113impl Default for Pointer {
114 fn default() -> Self {
115 Self {
116 steps: Vec::default(),
117 }
118 }
119}