### CBORPath Query Examples
Source: https://github.com/dahomey-technologies/cborpath-rs/blob/master/README.md
A collection of CBORPath queries applied to the bookstore data, illustrating various selection and filtering capabilities.
```APIDOC
## CBORPath Query Examples
This table shows some CBORPath queries that might be applied to the example data and their intended results.
| Syntax | Intended result |
|---------------------------------------------------------------------------------------------|-----------------------------------------------------------------|
| `["$", "store", "book", {"*": 1}, "author"]` | the authors of all books in the store |
| `["$", {"..": "author"}]` | all authors |
| `["$", "store", {"*": 1}]` | all things in store, which are some books and a red bicycle |
| `["$", "store", {"..": "price"}]` | the prices of everything in the store |
| `["$", {"..": "book"}, {"#": 2}] ` | the third book |
| `["$", {"..": "book"}, {"#": -1}]` | the last book in order |
| `["$", {"..": "book"}, [{"#": 0}, {"#": 1}]]` or `["$", {"..": "book"}, {":": [0, 2, 1]}]` | the first two books |
| `["$", {"..": "book"}, {"?": ["@", "isbn"]}]` | all books with an ISBN number |
| `["$", {"..": "book"}, {"?": {"<": [["@", "price"], 10.0]}}]` | all books cheaper than 10 |
| `["$", {"..": {"*": 1}}]` | all map item values and array elements contained in input value |
```
--------------------------------
### Querying CBOR Data with CborPath
Source: https://github.com/dahomey-technologies/cborpath-rs/blob/master/README.md
Demonstrates various ways to query CBOR data using the CborPath builder. Examples include selecting specific indices, slicing, filtering by key existence, and numerical comparisons.
```rust
let cbor_path = CborPath::builder()
.descendant(builder::segment().key("book"))
.child(builder::segment().index(0).index(1))
.build();
let results = cbor_path.read_from_bytes(&value)?;
let cbor_path = CborPath::builder()
.descendant(builder::segment().key("book"))
.slice(0, 2, 1)
.build();
let results = cbor_path.read_from_bytes(&value)?;
let cbor_path = CborPath::builder()
.descendant(builder::segment().key("book"))
.filter(builder::rel_path().key("isbn"))
.build();
let results = cbor_path.read_from_bytes(&value)?;
let cbor_path = CborPath::builder()
.descendant(builder::segment().key("book"))
.filter(builder::lt(
builder::sing_rel_path().key("price"),
builder::val(10.),
))
.build();
let results = cbor_path.read_from_bytes(&value)?;
let cbor_path = CborPath::builder()
.descendant(builder::segment().wildcard())
.build();
let results = cbor_path.read_from_bytes(&value)?;
```
--------------------------------
### Getting Paths to Matched Nodes in Rust
Source: https://context7.com/dahomey-technologies/cborpath-rs/llms.txt
Explains how to use the `get_paths` method to retrieve the exact paths to nodes that match a given CborPath. It also demonstrates manual Path construction and checking parent-child relationships between paths.
```rust
use cborpath::{CborPath, Path, builder};
use cbor_data::Cbor;
// Assume cbor_document is defined elsewhere and is of type Cbor
// let cbor_document: Cbor = ...;
// Build a path and get locations of matches
let cbor_path = CborPath::builder()
.key("store")
.key("book")
.wildcard()
.key("price")
.build();
// let paths: Vec = cbor_path.get_paths(&cbor_document);
// Example output:
// [store][book][0][price]
// [store][book][1][price]
// [store][book][2][price]
// Build a Path manually for comparison or other uses
let expected_path = Path::default()
.key("store")
.key("book")
.idx(0)
.key("price");
// Check if one path is parent of another
let parent = Path::default().key("store").key("book");
let child = Path::default().key("store").key("book").idx(0);
// assert!(parent.is_parent(&child));
```
--------------------------------
### Querying CBOR Data with CborPath
Source: https://github.com/dahomey-technologies/cborpath-rs/blob/master/README.md
Demonstrates how to build path queries using the CborPath builder to extract specific fields, nested values, and indexed items from a CBOR-encoded data structure. The examples utilize the cbor-diag crate for input and verification.
```rust
use cborpath::{CborPath, builder, Error};
use cbor_diag::parse_diag;
pub fn diag_to_bytes(cbor_diag_str: &str) -> Vec {
parse_diag(cbor_diag_str).unwrap().to_bytes()
}
fn main() -> Result<(), Error> {
let value = diag_to_bytes(r#"{ "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99 }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99 }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99 } ], "bicycle": { "color": "red", "price": 399 } } }"#);
let cbor_path = CborPath::builder()
.key("store")
.key("book")
.wildcard()
.key("author")
.build();
let results = cbor_path.read_from_bytes(&value)?;
Ok(())
}
```
--------------------------------
### CBORPath Expression Examples
Source: https://github.com/dahomey-technologies/cborpath-rs/blob/master/README.md
Demonstrates various CBORPath expressions for querying a CBOR data structure. These examples showcase different path segments and operators for selecting data, such as accessing nested fields, filtering arrays, and selecting elements by index or condition. The input is a JSON representation of a CBOR structure.
```json
["$", "store", "book", {"*": 1}, "author"]
```
```json
["$", {"..": "author"}]
```
```json
["$", "store", {"*": 1}]
```
```json
["$", "store", {"..": "price"}]
```
```json
["$", {"..": "book"}, {"#": 2}]
```
```json
["$", {"..": "book"}, {"#": -1}]
```
```json
["$", {"..": "book"}, [{"#": 0}, {"#": 1}]]
```
```json
["$", {"..": "book"}, {":": [0, 2, 1]}]
```
```json
["$", {"..": "book"}, {"?": ["@", "isbn"]}]
```
```json
["$", {"..": "book"}, {"?": {"<": [["@", "price"], 10.0]}}]
```
```json
["$", {"..": {"*": 1}}]
```
--------------------------------
### Getting Paths to Matched Nodes
Source: https://context7.com/dahomey-technologies/cborpath-rs/llms.txt
Explains how to use the `get_paths` method to retrieve the exact paths to nodes that match a CBORPath expression.
```APIDOC
## Getting Paths to Matched Nodes
The `get_paths` method returns the actual paths to matched nodes instead of the values, useful for understanding document structure or for subsequent modifications.
### Description
This section details how to obtain the specific CBORPath locations of elements that satisfy a given query. This is useful for debugging, analysis, or preparing for update operations.
### Method
`cbor_path.get_paths(&cbor_document)`
`Path::is_parent(&other_path)`
### Endpoint
N/A (This is a library usage example)
### Parameters
#### Request Body
N/A
### Request Example
```rust
use cborpath::{CborPath, Path, builder};
use cbor_data::Cbor;
// Assume `cbor_document` is a loaded CBOR data structure
// Build a path and get locations of matches
let cbor_path = CborPath::builder()
.key("store")
.key("book")
.wildcard()
.key("price")
.build();
let paths: Vec = cbor_path.get_paths(&cbor_document);
// Example `paths` output:
// [store][book][0][price]
// [store][book][1][price]
// [store][book][2][price]
// Build a Path manually for comparison or other uses
let expected_path = Path::default()
.key("store")
.key("book")
.idx(0)
.key("price");
// Check if one path is parent of another
let parent = Path::default().key("store").key("book");
let child = Path::default().key("store").key("book").idx(0);
assert!(parent.is_parent(&child));
```
### Response
N/A (This is a library usage example)
#### Success Response (200)
- **paths** (Vec) - A vector containing `Path` objects for each matched node.
#### Response Example
```json
[
"[store][book][0][price]",
"[store][book][1][price]",
"[store][book][2][price]"
]
```
```
--------------------------------
### Deleting Values at Path Locations in Rust
Source: https://context7.com/dahomey-technologies/cborpath-rs/llms.txt
Demonstrates the `delete` method for removing values at locations matching a CborPath from a CBOR document. Examples include deleting a key from a map, an element from an array by index, nested elements, and handling cases where the path does not match.
```rust
use cborpath::{CborPath, builder};
// Assume cbor, cbor_array, and cbor_nested are defined elsewhere and are of type Cbor
// let cbor: Cbor = ...;
// let cbor_array: Cbor = ...;
// let cbor_nested: Cbor = ...;
// Delete a single key from a map
// Original: {"a": 1, "b": 2}
let cbor_path = CborPath::builder().key("b").build();
// let result = cbor_path.delete(&cbor).unwrap();
// Result: {"a": 1}
// Delete an array element by index
// Original: ["a", "b", "c"]
let array_path = CborPath::builder().index(1).build();
// let result = array_path.delete(&cbor_array).unwrap();
// Result: ["a", "c"]
// Delete nested elements
// Original: {"foo": {"a": {"b": 1}, "c": 2}}
let nested_path = CborPath::builder().key("foo").key("a").build();
// let result = nested_path.delete(&cbor_nested).unwrap();
// Result: {"foo": {"c": 2}}
// Delete returns None if path doesn't match
let no_match = CborPath::builder().key("nonexistent").build();
// let result = no_match.delete(&cbor);
// assert!(result.is_none());
```
--------------------------------
### Filter Selectors with Existence Tests in Rust
Source: https://context7.com/dahomey-technologies/cborpath-rs/llms.txt
Filter selectors use boolean expressions to select elements matching specific conditions. A path by itself acts as an existence test, returning elements where the specified path exists. This example shows filtering books with and without an 'isbn' field.
```Rust
use cborpath::{CborPath, builder};
// Select all books that have an ISBN field (existence test)
// CBORPath: ["$", {"..": "book"}, {"?": ["@", "isbn"]}]
let cbor_path = CborPath::builder()
.descendant(builder::segment().key("book"))
.filter(builder::rel_path().key("isbn"))
.build();
let books_with_isbn = cbor_path.read(&cbor_document);
// Returns only books where the "isbn" key exists
// Filter with negated existence (books WITHOUT isbn)
let no_isbn_path = CborPath::builder()
.descendant(builder::segment().key("book"))
.filter(builder::not(builder::rel_path().key("isbn")))
.build();
```
--------------------------------
### Descendant Selector for Deep Queries in Rust
Source: https://context7.com/dahomey-technologies/cborpath-rs/llms.txt
The descendant selector (`..`) recursively searches nested structures for matching elements. It's useful for finding keys at any depth within a CBOR document. This example demonstrates finding all 'author' and 'price' keys.
```Rust
use cborpath::{CborPath, builder};
// Build a path that finds all "author" keys anywhere in the document
// CBORPath: ["$", {"..": "author"}]
let cbor_path = CborPath::builder()
.descendant(builder::segment().key("author"))
.build();
// This will find authors at any nesting level in the CBOR structure
let results = cbor_path.read(&cbor_document);
// Find all prices in the entire document
// CBORPath: ["$", "store", {"..": "price"}]
let price_path = CborPath::builder()
.key("store")
.descendant(builder::segment().key("price"))
.build();
let all_prices = price_path.read(&cbor_document);
// Returns prices from books AND bicycle
```
--------------------------------
### Regular Expression Matching
Source: https://context7.com/dahomey-technologies/cborpath-rs/llms.txt
Demonstrates how to use `_match` for exact string matching and `search` for substring matching with regular expressions in CBORPath filters.
```APIDOC
## Regular Expression Matching with match and search
Use `_match` for full string matching and `search` for substring matching with regular expressions.
### Description
This section shows how to filter CBOR data based on regular expression patterns applied to specific fields. `_match` performs an exact match (anchored), while `search` finds patterns anywhere within the string.
### Method
`CborPath::builder().filter(builder::_match(...))` for exact matching.
`CborPath::builder().filter(builder::search(...))` for substring matching.
### Endpoint
N/A (This is a library usage example)
### Parameters
#### Request Body
N/A
### Request Example
```rust
use cborpath::{CborPath, builder, Error};
fn main() -> Result<(), Error> {
// Select books where author name matches pattern exactly
// Uses _match for full string match (anchored with ^ and $)
let cbor_path = CborPath::builder()
.descendant(builder::segment().key("book"))
.filter(builder::_match(
builder::sing_rel_path().key("author"),
r"J\. R\. R\. .*".to_string(), // Matches "J. R. R. Tolkien"
)?)
.build();
// Select books where title contains "Lord" anywhere
// Uses search for substring match
let search_path = CborPath::builder()
.descendant(builder::segment().key("book"))
.filter(builder::search(
builder::sing_rel_path().key("title"),
"Lord".to_string(), // Matches "The Lord of the Rings"
)?)
.build();
// Case-insensitive search using regex flags
let case_insensitive_path = CborPath::builder()
.descendant(builder::segment().key("book"))
.filter(builder::search(
builder::sing_rel_path().key("title"),
"(?i)moby".to_string(), // Matches "Moby Dick" case-insensitively
)?)
.build();
Ok(())
}
```
### Response
N/A (This is a library usage example)
#### Success Response (200)
N/A
#### Response Example
N/A
```
--------------------------------
### Initialize CborPath from CBOR Data
Source: https://context7.com/dahomey-technologies/cborpath-rs/llms.txt
Shows how to create a CborPath instance from existing CBOR-encoded values or raw byte slices. This is useful for deserializing paths stored in external systems.
```rust
let path_cbor = CborBuilder::new().write_array(None, |builder| {
builder.write_str("$", None);
builder.write_str("store", None);
builder.write_str("book", None);
});
let cbor_path = CborPath::from_value(&path_cbor)?;
let cbor_path_from_bytes = CborPath::from_bytes(path_cbor.as_ref())?;
let root_path = CborPath::root();
```
--------------------------------
### Regex Matching with cborpath in Rust
Source: https://context7.com/dahomey-technologies/cborpath-rs/llms.txt
Demonstrates using `_match` for exact string matching and `search` for substring matching with regular expressions in CBORPath. It shows how to build CborPath objects with filters for specific conditions on keys like 'author' and 'title', including case-insensitive matching.
```rust
use cborpath::{CborPath, builder, Error};
fn main() -> Result<(), Error> {
// Select books where author name matches pattern exactly
// Uses _match for full string match (anchored with ^ and $)
let cbor_path = CborPath::builder()
.descendant(builder::segment().key("book"))
.filter(builder::_match(
builder::sing_rel_path().key("author"),
r"J\. R\. R\. .*".to_string(), // Matches "J. R. R. Tolkien"
)?)
.build();
// Select books where title contains "Lord" anywhere
// Uses search for substring match
let search_path = CborPath::builder()
.descendant(builder::segment().key("book"))
.filter(builder::search(
builder::sing_rel_path().key("title"),
"Lord".to_string(), // Matches "The Lord of the Rings"
)?)
.build();
// Case-insensitive search using regex flags
let case_insensitive_path = CborPath::builder()
.descendant(builder::segment().key("book"))
.filter(builder::search(
builder::sing_rel_path().key("title"),
"(?i)moby".to_string(), // Matches "Moby Dick" case-insensitively
)?)
.build();
Ok(())
}
```
--------------------------------
### Constructing and Executing Path Expressions
Source: https://context7.com/dahomey-technologies/cborpath-rs/llms.txt
Demonstrates how to use the CborPath builder pattern to define a path expression and query a structured CBOR object. This approach is ideal for navigating nested maps and arrays within a CBOR document.
```rust
use cborpath::{CborPath, builder};
use cbor_data::{CborBuilder, Writer, Cbor};
let value = CborBuilder::new().write_dict(None, |builder| {
builder.with_key("store", |builder| {
builder.write_dict(None, |builder| {
builder.with_key("book", |builder| {
builder.write_array(None, |builder| {
builder.write_dict(None, |b| {
b.with_key("category", |b| b.write_str("reference", None));
b.with_key("author", |b| b.write_str("Nigel Rees", None));
b.with_key("title", |b| b.write_str("Sayings of the Century", None));
b.with_key("price", |b| b.write_lit(cbor_data::Literal::L8(8.95_f64.to_bits()), None));
});
builder.write_dict(None, |b| {
b.with_key("category", |b| b.write_str("fiction", None));
b.with_key("author", |b| b.write_str("Herman Melville", None));
b.with_key("title", |b| b.write_str("Moby Dick", None));
b.with_key("price", |b| b.write_lit(cbor_data::Literal::L8(8.99_f64.to_bits()), None));
});
});
});
builder.with_key("bicycle", |builder| {
builder.write_dict(None, |b| {
b.with_key("color", |b| b.write_str("red", None));
b.with_key("price", |b| b.write_pos(399, None));
});
});
});
});
});
let cbor_path = CborPath::builder()
.key("store")
.key("book")
.wildcard()
.key("author")
.build();
let results = cbor_path.read(&value);
```
--------------------------------
### Handle Library Errors
Source: https://context7.com/dahomey-technologies/cborpath-rs/llms.txt
Illustrates how to catch and handle specific error variants such as parsing, conversion, and write failures. It also demonstrates error handling during complex path construction like regex filters.
```rust
match cbor_path.read_from_bytes(data) {
Ok(results) => Ok(results),
Err(Error::Parsing(msg)) => Err(Error::Parsing(msg)),
Err(Error::Conversion(msg)) => Err(Error::Conversion(msg)),
Err(Error::Write(msg)) => Err(Error::Write(msg)),
}
fn create_search_filter(pattern: &str) -> Result {
let cbor_path = CborPath::builder()
.filter(builder::search(builder::sing_rel_path().key("name"), pattern)?)
.build();
Ok(cbor_path)
}
```
--------------------------------
### Setting Values at Path Locations
Source: https://context7.com/dahomey-technologies/cborpath-rs/llms.txt
Demonstrates how to use the `set` method to update or insert values at specified locations within a CBOR document.
```APIDOC
## Setting Values at Path Locations
The `set` method replaces values at all locations matching the path with a new value.
### Description
This section explains how to modify CBOR data by providing a CBORPath and a new value. The `set` method will update existing values or insert new ones if the path implies it, returning the modified document or `None` if no matches were found.
### Method
`cbor_path.set(&cbor_document, &new_value)`
### Endpoint
N/A (This is a library usage example)
### Parameters
#### Request Body
- **cbor_document** (CborOwned) - The CBOR data to modify.
- **new_value** (CborOwned) - The new value to set at the matched paths.
### Request Example
```rust
use cborpath::{CborPath, builder};
use cborpath::builder::IntoCborOwned;
use cbor_data::CborOwned;
// Assume `cbor` and `cbor_document` are loaded CBOR data structures
// Create new value to set
let new_value: CborOwned = IntoCborOwned::into(3);
// Replace value at path ["$", "b"]
let cbor_path = CborPath::builder().key("b").build();
let result = cbor_path.set(&cbor, &new_value);
// Example result: {"a": 1, "b": 3}
// Replace all book prices in a nested structure
let price_path = CborPath::builder()
.descendant(builder::segment().key("book"))
.wildcard()
.key("price")
.build();
let discount_price: CborOwned = IntoCborOwned::into(9.99);
let updated = price_path.set(&cbor_document, &discount_price);
// Example `updated` content: All book prices are now 9.99
// Set returns None if no matches found
let no_match_path = CborPath::builder().key("nonexistent").build();
let result = no_match_path.set(&cbor, &new_value);
assert!(result.is_none());
```
### Response
- **Option** - Returns `Some(CborOwned)` containing the modified CBOR document if matches were found, otherwise returns `None`.
#### Success Response (200)
- **modified_document** (CborOwned) - The CBOR document with values updated at the specified paths.
#### Response Example
```json
{
"a": 1,
"b": 3
}
```
```
--------------------------------
### CBOR Data Structure
Source: https://github.com/dahomey-technologies/cborpath-rs/blob/master/README.md
The sample CBOR data structure representing a bookstore, used for demonstrating CBORPath queries.
```APIDOC
## CBOR Data Structure
This is the sample CBOR data structure used for the examples.
```json
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 399
}
}
}
```
```
--------------------------------
### Perform Custom Write Operations with Closures
Source: https://context7.com/dahomey-technologies/cborpath-rs/llms.txt
Demonstrates how to use the write method to modify, append, or increment values within a CBOR document. It uses closures to inspect existing data types and return transformed results.
```rust
fn array_append<'a>(cbor_path: &CborPath, cbor: &'a Cbor, value: &'a Cbor) -> Result