Skip to content

Commit b423489

Browse files
authored
Slicing API for Pointer (#84)
* implement slicing api * update changelog * add note about complexity of indexing tokens
1 parent adfc513 commit b423489

File tree

3 files changed

+523
-6
lines changed

3 files changed

+523
-6
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
2020

2121
- Changed signature of `PathBuf::parse` to avoid requiring allocation.
2222
- Bumps minimum Rust version to 1.79.
23+
- `Pointer::get` now accepts ranges and can produce `Pointer` segments as output (similar to
24+
`slice::get`).
2325

2426
### Fixed
2527

src/pointer.rs

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ use alloc::{
77
vec::Vec,
88
};
99
use core::{borrow::Borrow, cmp::Ordering, ops::Deref, str::FromStr};
10+
use slice::SlicePointer;
11+
12+
mod slice;
1013

1114
/*
1215
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
@@ -277,23 +280,35 @@ impl Pointer {
277280
.map(|s| unsafe { Self::new_unchecked(s) })
278281
}
279282

280-
/// Attempts to get a `Token` by the index. Returns `None` if the index is
281-
/// out of bounds.
283+
/// Attempts to get a `Token` or a segment of the `Pointer`, depending on
284+
/// the type of index.
285+
///
286+
/// Returns `None` if the index is out of bounds.
287+
///
288+
/// Note that this operation is O(n).
282289
///
283290
/// ## Example
284291
/// ```rust
285292
/// use jsonptr::{Pointer, Token};
286293
///
287-
/// let ptr = Pointer::from_static("/foo/bar");
294+
/// let ptr = Pointer::from_static("/foo/bar/qux");
288295
/// assert_eq!(ptr.get(0), Some("foo".into()));
289296
/// assert_eq!(ptr.get(1), Some("bar".into()));
290-
/// assert_eq!(ptr.get(2), None);
297+
/// assert_eq!(ptr.get(3), None);
298+
/// assert_eq!(ptr.get(..), Some(Pointer::from_static("/foo/bar/qux")));
299+
/// assert_eq!(ptr.get(..1), Some(Pointer::from_static("/foo")));
300+
/// assert_eq!(ptr.get(1..3), Some(Pointer::from_static("/bar/qux")));
301+
/// assert_eq!(ptr.get(1..=2), Some(Pointer::from_static("/bar/qux")));
291302
///
292303
/// let ptr = Pointer::root();
293304
/// assert_eq!(ptr.get(0), None);
305+
/// assert_eq!(ptr.get(..), Some(Pointer::root()));
294306
/// ```
295-
pub fn get(&self, index: usize) -> Option<Token> {
296-
self.tokens().nth(index).clone()
307+
pub fn get<'p, I>(&'p self, index: I) -> Option<I::Output>
308+
where
309+
I: SlicePointer<'p>,
310+
{
311+
index.get(self)
297312
}
298313

299314
/// Attempts to resolve a [`R::Value`] based on the path in this [`Pointer`].

0 commit comments

Comments
 (0)