parquet_variant/
path.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17use std::{borrow::Cow, ops::Deref};
18
19/// Represents a qualified path to a potential subfield or index of a variant
20/// value.
21///
22/// Can be used with [`Variant::get_path`] to retrieve a specific subfield of
23/// a variant value.
24///
25/// [`Variant::get_path`]: crate::Variant::get_path
26///
27/// Create a [`VariantPath`] from a vector of [`VariantPathElement`], or
28/// from a single field name or index.
29///
30/// # Example: Simple paths
31/// ```rust
32/// # use parquet_variant::{VariantPath, VariantPathElement};
33/// // access the field "foo" in a variant object value
34/// let path = VariantPath::from("foo");
35/// // access the first element in a variant list vale
36/// let path = VariantPath::from(0);
37/// ```
38///
39/// # Example: Compound paths
40/// ```
41/// # use parquet_variant::{VariantPath, VariantPathElement};
42/// /// You can also create a path by joining elements together:
43/// // access the field "foo" and then the first element in a variant list value
44/// let path = VariantPath::from("foo").join(0);
45/// // this is the same as the previous one
46/// let path2 = VariantPath::from_iter(["foo".into(), 0.into()]);
47/// assert_eq!(path, path2);
48/// // you can also create a path from a vector of `VariantPathElement` directly
49/// let path3 = [
50///   VariantPathElement::field("foo"),
51///   VariantPathElement::index(0)
52/// ].into_iter().collect::<VariantPath>();
53/// assert_eq!(path, path3);
54/// ```
55///
56/// # Example: Accessing Compound paths
57/// ```
58/// # use parquet_variant::{VariantPath, VariantPathElement};
59/// /// You can access the paths using slices
60/// // access the field "foo" and then the first element in a variant list value
61/// let path = VariantPath::from("foo")
62///   .join("bar")
63///   .join("baz");
64/// assert_eq!(path[1], VariantPathElement::field("bar"));
65/// ```
66#[derive(Debug, Clone, PartialEq, Default)]
67pub struct VariantPath<'a>(Vec<VariantPathElement<'a>>);
68
69impl<'a> VariantPath<'a> {
70    /// Create a new `VariantPath` from a vector of `VariantPathElement`.
71    pub fn new(path: Vec<VariantPathElement<'a>>) -> Self {
72        Self(path)
73    }
74
75    /// Return the inner path elements.
76    pub fn path(&self) -> &Vec<VariantPathElement<'_>> {
77        &self.0
78    }
79
80    /// Return a new `VariantPath` with element appended
81    pub fn join(mut self, element: impl Into<VariantPathElement<'a>>) -> Self {
82        self.push(element);
83        self
84    }
85
86    /// Append a new element to the path
87    pub fn push(&mut self, element: impl Into<VariantPathElement<'a>>) {
88        self.0.push(element.into());
89    }
90
91    /// Returns whether [`VariantPath`] has no path elements
92    pub fn is_empty(&self) -> bool {
93        self.0.is_empty()
94    }
95}
96
97impl<'a> From<Vec<VariantPathElement<'a>>> for VariantPath<'a> {
98    fn from(value: Vec<VariantPathElement<'a>>) -> Self {
99        Self::new(value)
100    }
101}
102
103/// Create from &str with support for dot notation
104impl<'a> From<&'a str> for VariantPath<'a> {
105    fn from(path: &'a str) -> Self {
106        VariantPath::new(path.split('.').map(Into::into).collect())
107    }
108}
109
110/// Create from usize
111impl<'a> From<usize> for VariantPath<'a> {
112    fn from(index: usize) -> Self {
113        VariantPath::new(vec![VariantPathElement::index(index)])
114    }
115}
116
117impl<'a> From<&[VariantPathElement<'a>]> for VariantPath<'a> {
118    fn from(elements: &[VariantPathElement<'a>]) -> Self {
119        VariantPath::new(elements.to_vec())
120    }
121}
122
123/// Create from iter
124impl<'a> FromIterator<VariantPathElement<'a>> for VariantPath<'a> {
125    fn from_iter<T: IntoIterator<Item = VariantPathElement<'a>>>(iter: T) -> Self {
126        VariantPath::new(Vec::from_iter(iter))
127    }
128}
129
130impl<'a> Deref for VariantPath<'a> {
131    type Target = [VariantPathElement<'a>];
132
133    fn deref(&self) -> &Self::Target {
134        &self.0
135    }
136}
137
138/// Element of a [`VariantPath`] that can be a field name or an index.
139///
140/// See [`VariantPath`] for more details and examples.
141#[derive(Debug, Clone, PartialEq)]
142pub enum VariantPathElement<'a> {
143    /// Access field with name `name`
144    Field { name: Cow<'a, str> },
145    /// Access the list element at `index`
146    Index { index: usize },
147}
148
149impl<'a> VariantPathElement<'a> {
150    pub fn field(name: impl Into<Cow<'a, str>>) -> VariantPathElement<'a> {
151        let name = name.into();
152        VariantPathElement::Field { name }
153    }
154
155    pub fn index(index: usize) -> VariantPathElement<'a> {
156        VariantPathElement::Index { index }
157    }
158}
159
160// Conversion utilities for `VariantPathElement` from string types
161impl<'a> From<Cow<'a, str>> for VariantPathElement<'a> {
162    fn from(name: Cow<'a, str>) -> Self {
163        VariantPathElement::field(name)
164    }
165}
166
167impl<'a> From<&'a str> for VariantPathElement<'a> {
168    fn from(name: &'a str) -> Self {
169        VariantPathElement::field(Cow::Borrowed(name))
170    }
171}
172
173impl<'a> From<String> for VariantPathElement<'a> {
174    fn from(name: String) -> Self {
175        VariantPathElement::field(Cow::Owned(name))
176    }
177}
178
179impl<'a> From<&'a String> for VariantPathElement<'a> {
180    fn from(name: &'a String) -> Self {
181        VariantPathElement::field(Cow::Borrowed(name.as_str()))
182    }
183}
184
185impl<'a> From<usize> for VariantPathElement<'a> {
186    fn from(index: usize) -> Self {
187        VariantPathElement::index(index)
188    }
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194
195    #[test]
196    fn test_variant_path_empty() {
197        let path = VariantPath::from_iter([]);
198        assert!(path.is_empty());
199    }
200
201    #[test]
202    fn test_variant_path_non_empty() {
203        let p = VariantPathElement::from("a");
204        let path = VariantPath::from_iter([p]);
205        assert!(!path.is_empty());
206    }
207}