Skip to content

Commit

Permalink
Slicing API for Pointer (#84)
Browse files Browse the repository at this point in the history
* implement slicing api

* update changelog

* add note about complexity of indexing tokens
  • Loading branch information
asmello authored Oct 21, 2024
1 parent adfc513 commit b423489
Show file tree
Hide file tree
Showing 3 changed files with 523 additions and 6 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

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

### Fixed

Expand Down
27 changes: 21 additions & 6 deletions src/pointer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ use alloc::{
vec::Vec,
};
use core::{borrow::Borrow, cmp::Ordering, ops::Deref, str::FromStr};
use slice::SlicePointer;

mod slice;

/*
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
Expand Down Expand Up @@ -277,23 +280,35 @@ impl Pointer {
.map(|s| unsafe { Self::new_unchecked(s) })
}

/// Attempts to get a `Token` by the index. Returns `None` if the index is
/// out of bounds.
/// Attempts to get a `Token` or a segment of the `Pointer`, depending on
/// the type of index.
///
/// Returns `None` if the index is out of bounds.
///
/// Note that this operation is O(n).
///
/// ## Example
/// ```rust
/// use jsonptr::{Pointer, Token};
///
/// let ptr = Pointer::from_static("/foo/bar");
/// let ptr = Pointer::from_static("/foo/bar/qux");
/// assert_eq!(ptr.get(0), Some("foo".into()));
/// assert_eq!(ptr.get(1), Some("bar".into()));
/// assert_eq!(ptr.get(2), None);
/// assert_eq!(ptr.get(3), None);
/// assert_eq!(ptr.get(..), Some(Pointer::from_static("/foo/bar/qux")));
/// assert_eq!(ptr.get(..1), Some(Pointer::from_static("/foo")));
/// assert_eq!(ptr.get(1..3), Some(Pointer::from_static("/bar/qux")));
/// assert_eq!(ptr.get(1..=2), Some(Pointer::from_static("/bar/qux")));
///
/// let ptr = Pointer::root();
/// assert_eq!(ptr.get(0), None);
/// assert_eq!(ptr.get(..), Some(Pointer::root()));
/// ```
pub fn get(&self, index: usize) -> Option<Token> {
self.tokens().nth(index).clone()
pub fn get<'p, I>(&'p self, index: I) -> Option<I::Output>
where
I: SlicePointer<'p>,
{
index.get(self)
}

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

0 comments on commit b423489

Please sign in to comment.