Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Slicing API for Pointer #84

Merged
merged 3 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,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`).

## [0.6.2] 2024-09-30

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
Loading