### 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, Error> { cbor_path.write(cbor, |old_value| { if let ItemKind::Array(array) = old_value.kind() { Ok(Some(Cow::Owned(CborBuilder::new().write_array(None, |builder| { for item in array { builder.write_item(item); } builder.write_item(value); })))) } else { Ok(Some(Cow::Borrowed(old_value))) } }) } fn increment_value(cbor_path: &CborPath, cbor: &Cbor) -> Result, Error> { cbor_path.write(cbor, |old_value| { if let ItemKind::Pos(n) = old_value.kind() { Ok(Some(Cow::Owned(CborBuilder::new().write_pos(n + 1, None)))) } else { Ok(Some(Cow::Borrowed(old_value))) } }) } ``` -------------------------------- ### Setting Values at Path Locations in Rust Source: https://context7.com/dahomey-technologies/cborpath-rs/llms.txt Illustrates the use of the `set` method to replace values at all locations matching a CborPath with a new CBOR value. It covers setting a single value, updating multiple values in a nested structure, and handling cases where no matches are found. ```rust use cborpath::{CborPath, builder}; use cborpath::builder::IntoCborOwned; use cbor_data::CborOwned; // Assume cbor and cbor_document are defined elsewhere and are of type Cbor // let cbor: Cbor = ...; // let cbor_document: Cbor = ...; // 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); // 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()); ``` -------------------------------- ### Rust: Combine Filters with Logical Operators (AND, OR, NOT) Source: https://context7.com/dahomey-technologies/cborpath-rs/llms.txt Shows how to combine multiple filter conditions using logical AND, OR, and NOT operators in CBORPath. This allows for the creation of complex queries to precisely select data. ```rust use cborpath::{CborPath, builder}; // Select fiction books cheaper than 15 // Combines AND logic: category == "fiction" AND price < 15 let cbor_path = CborPath::builder() .descendant(builder::segment().key("book")) .filter(builder::and( builder::eq( builder::sing_rel_path().key("category"), builder::val("fiction"), ), builder::lt( builder::sing_rel_path().key("price"), builder::val(15.0), ), )) .build(); // Select reference books OR books with ISBN // Uses OR logic let ref_or_isbn_path = CborPath::builder() .descendant(builder::segment().key("book")) .filter(builder::or( builder::eq( builder::sing_rel_path().key("category"), builder::val("reference"), ), builder::rel_path().key("isbn"), )) .build(); // Complex nested logic: (category == "fiction" AND price < 10) OR has ISBN let complex_path = CborPath::builder() .descendant(builder::segment().key("book")) .filter(builder::or( builder::and( builder::eq(builder::sing_rel_path().key("category"), builder::val("fiction")), builder::lt(builder::sing_rel_path().key("price"), builder::val(10.0)), ), builder::rel_path().key("isbn"), )) .build(); ``` -------------------------------- ### Rust: Filter CBOR Data with Comparison Operators Source: https://context7.com/dahomey-technologies/cborpath-rs/llms.txt Demonstrates using comparison operators (<, <=, ==, !=, >=, >) in CBORPath to filter elements based on value comparisons. This is useful for selecting data that meets specific numerical or string criteria. ```rust use cborpath::{CborPath, builder}; // Select all books cheaper than 10 // CBORPath: ["$", {"..": "book"}, {"?": {"<": [["@", "price"], 10.0]}}] let cbor_path = CborPath::builder() .descendant(builder::segment().key("book")) .filter(builder::lt( builder::sing_rel_path().key("price"), builder::val(10.0), )) .build(); let cheap_books = cbor_path.read(&cbor_document); // Select books with price greater than or equal to 20 let expensive_books_path = CborPath::builder() .descendant(builder::segment().key("book")) .filter(builder::gte( builder::sing_rel_path().key("price"), builder::val(20.0), )) .build(); // Select books with a specific category let fiction_path = CborPath::builder() .descendant(builder::segment().key("book")) .filter(builder::eq( builder::sing_rel_path().key("category"), builder::val("fiction"), )) .build(); // Select books where price doesn't equal 8.99 let not_price_path = CborPath::builder() .descendant(builder::segment().key("book")) .filter(builder::neq( builder::sing_rel_path().key("price"), builder::val(8.99), )) .build(); ``` -------------------------------- ### Singular Segments Source: https://github.com/dahomey-technologies/cborpath-rs/blob/master/README.md Explains the syntax for singular segments used in paths to select specific CBOR elements. ```APIDOC ## Singular Segment A `singular segment` produces a nodelist containing at most one node. ### Syntax - ``, ``, ``, ``, ``, ``: `key selector` - selects a child of a CBOR Map based on the child key. - `{"#": }`: `index selector` - selects an indexed child of an array (from 0). ``` -------------------------------- ### Define Test Data Structure for CBORPath Source: https://github.com/dahomey-technologies/cborpath-rs/blob/master/README.md This snippet demonstrates a Rust test case structure containing a collection of book objects and primitive values. It is intended to be used as a target for path-based queries to verify the library's parsing and selection capabilities. ```rust let data = vec![ { "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 } ]; ``` -------------------------------- ### Rust: Utilize Built-in Functions length and count Source: https://context7.com/dahomey-technologies/cborpath-rs/llms.txt Explains the usage of the `length` and `count` built-in functions in CBORPath. `length` returns the size of collections or strings, while `count` returns the number of nodes matched by a path. ```rust use cborpath::{CborPath, builder}; // Select items where the "authors" array has 5 or more elements // CBORPath: ["$", {"?": {uyorum": [{"length": ["@", "authors"]}, 5]}}] let cbor_path = CborPath::builder() .filter(builder::gte( builder::length(builder::sing_rel_path().key("authors")), builder::val(5_u64), )) .build(); // Select books where title length is greater than 10 characters let long_title_path = CborPath::builder() .descendant(builder::segment().key("book")) .filter(builder::gt( builder::length(builder::sing_rel_path().key("title")), builder::val(10_u64), )) .build(); // Select items where the count of matching paths equals a value // CBORPath: ["$", {"?": {uyorum": [{"count": ["@", "authors"]}, 5]}}] let count_path = CborPath::builder() .filter(builder::gte( builder::count(builder::rel_path().key("tags")), builder::val(3_u64), )) .build(); ``` -------------------------------- ### POST /cbor/query Source: https://github.com/dahomey-technologies/cborpath-rs/blob/master/README.md Executes a CBORPath query against a provided CBOR byte stream to extract specific data elements. ```APIDOC ## POST /cbor/query ### Description Executes a structured query against a CBOR byte array. The query uses a builder pattern to define path segments, filters, and slices. ### Method POST ### Endpoint /cbor/query ### Parameters #### Request Body - **cbor_data** (bytes) - Required - The raw CBOR encoded data. - **query_builder** (object) - Required - The path definition using builder methods like descendant, child, slice, or filter. ### Request Example { "cbor_data": "0xA164626F6F6B...", "query": { "descendant": "book", "filter": {"price": {"$lt": 10}} } } ### Response #### Success Response (200) - **results** (array) - The list of CBOR elements matching the query criteria. #### Response Example [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 } ] ``` -------------------------------- ### Querying Serialized CBOR Bytes Source: https://context7.com/dahomey-technologies/cborpath-rs/llms.txt Shows how to apply a CborPath expression directly to a raw byte vector containing serialized CBOR data. This is useful for high-performance applications processing binary data streams. ```rust use cborpath::{CborPath, builder, Error}; fn main() -> Result<(), Error> { let cbor_bytes: Vec = vec![ 0xA1, 0x65, 0x73, 0x74, 0x6F, 0x72, 0x65, 0xA1, 0x64, 0x62, 0x6F, 0x6F, 0x6B, 0x82, 0xA2, 0x65, 0x74, 0x69, 0x74, 0x6C, 0x65, 0x64, 0x42, 0x6F, 0x6F, 0x6B, 0x31, 0x65, 0x70, 0x72, 0x69, 0x63, 0x65, 0x0A, 0xA2, 0x65, 0x74, 0x69, 0x74, 0x6C, 0x65, 0x64, 0x42, 0x6F, 0x6F, 0x6B, 0x32, 0x65, 0x70, 0x72, 0x69, 0x63, 0x65, 0x14 ]; let cbor_path = CborPath::builder() .key("store") .key("book") .wildcard() .key("title") .build(); let result_bytes = cbor_path.read_from_bytes(&cbor_bytes)?; Ok(()) } ``` -------------------------------- ### Comparable Types Source: https://github.com/dahomey-technologies/cborpath-rs/blob/master/README.md Details the types of values that can be used as operands in comparisons or as arguments to functions. ```APIDOC ## Comparable A `comparable` is an operand of a `filter` comparison or an argument of a function. ### Syntax - ``, ``, ``, ``, ``, ``: a `CBOR` value. - `["$", ]`, `["@", ]`: a singular path (a path that produces a nodelist containing at most one node). - `{"length": }`: length function to compute the length of a value. Returns an unsigned integer. - `{"count": }`: count function to compute the number of nodes in a path. Returns an unsigned integer. - `{"value": }`: value function to get the value of a single node path. Returns a `CBOR` value. ``` -------------------------------- ### Deleting Values at Path Locations Source: https://context7.com/dahomey-technologies/cborpath-rs/llms.txt Illustrates how to use the `delete` method to remove elements from a CBOR document based on a CBORPath. ```APIDOC ## Deleting Values at Path Locations The `delete` method removes values at all locations matching the path from the CBOR document. ### Description This section covers the removal of data from CBOR documents using CBORPath. The `delete` method targets elements specified by the path and removes them, returning the modified document or `None` if the path does not match any elements. ### Method `cbor_path.delete(&cbor_document)` ### Endpoint N/A (This is a library usage example) ### Parameters #### Request Body - **cbor_document** (CborOwned) - The CBOR data from which to delete. ### Request Example ```rust use cborpath::{CborPath, builder}; // Assume `cbor`, `cbor_array`, and `cbor_nested` are loaded CBOR data structures // 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()); ``` ### Response - **Option** - Returns `Some(CborOwned)` containing the modified CBOR document if matches were found and deleted, otherwise returns `None`. #### Success Response (200) - **modified_document** (CborOwned) - The CBOR document with the specified elements removed. #### Response Example ```json { "a": 1 } ``` ``` -------------------------------- ### Index and Slice Selectors for Arrays in Rust Source: https://context7.com/dahomey-technologies/cborpath-rs/llms.txt Index selectors access specific array elements (including negative indices), while slice selectors extract ranges of elements with optional step values. This allows for precise or ranged access to array data. ```Rust use cborpath::{CborPath, builder}; // Select the third book (index 2, zero-based) // CBORPath: ["$", {"..": "book"}, {"#": 2}] let cbor_path = CborPath::builder() .descendant(builder::segment().key("book")) .index(2) .build(); // Select the last book using negative index // CBORPath: ["$", {"..": "book"}, {"#": -1}] let last_book_path = CborPath::builder() .descendant(builder::segment().key("book")) .index(-1) .build(); // Select first two books using slice [start, end, step] // CBORPath: ["$", {"..": "book"}, {":": [0, 2, 1]}] let first_two_path = CborPath::builder() .descendant(builder::segment().key("book")) .slice(0, 2, 1) .build(); // Select every other book starting from index 0 let every_other_path = CborPath::builder() .descendant(builder::segment().key("book")) .slice(0, 10, 2) .build(); // Reverse order selection with negative step let reverse_path = CborPath::builder() .descendant(builder::segment().key("book")) .slice(3, 0, -1) .build(); ``` -------------------------------- ### Boolean Expressions Source: https://github.com/dahomey-technologies/cborpath-rs/blob/master/README.md Defines the syntax and usage of boolean expressions for filtering CBOR data. ```APIDOC ## Boolean Expressions A boolean expression returns `true` or `false` and is used by a `filter selector` to filter array elements or map items. ### Syntax - `{"&&": [, ]}`: logical `AND` - `{"||": [, ]}`: logical `OR` - `{"!": }`: logical `NOT` - `{">= ": [, ]}`: comparison `greater than or equal` - `{">": [, ]}`: comparison `greater than` - `{"==": [, ]}`: comparison `equal` - `{"!=": [, ]}`: comparison `not equal` - `{"<=": [, ]}`: comparison `lesser than or equal` - `{"<": [, ]}`: comparison `lesser than` - `{"match": [, ]}`: match function to compute a regular expression full match. Returns a boolean. - `{"search": [, ]}`: length function to compute a regular expression substring match. Returns a boolean. ``` -------------------------------- ### CBORPath Comparable Operands Source: https://github.com/dahomey-technologies/cborpath-rs/blob/master/README.md A comparable is an operand for filter comparisons or an argument for functions. It can be a CBOR value, a singular path, or the result of a length or count function. ```json ["$", ] ["@", ] {"length": } {"count": } {"value": } ``` -------------------------------- ### Multiple Selectors in a Single Segment in Rust Source: https://context7.com/dahomey-technologies/cborpath-rs/llms.txt Combine multiple selectors within a single segment using the child segment builder. This allows selecting elements that match any of the specified criteria, such as multiple indices or keys. ```Rust use cborpath::{CborPath, builder}; // Select both the first and second book using multiple index selectors // CBORPath: ["$", {"..": "book"}, [{"#": 0}, {"#": 1}]] let cbor_path = CborPath::builder() .descendant(builder::segment().key("book")) .child(builder::segment().index(0).index(1)) .build(); let first_two_books = cbor_path.read(&cbor_document); // Combine key selectors to get multiple properties let multi_key_path = CborPath::builder() .key("store") .key("book") .index(0) .child(builder::segment().key("title").key("author")) .build(); // Returns both title and author of the first book ```