Skip to main content

Crate kv_pairs

Crate kv_pairs 

Source
Expand description

Key-value pair builder for API params and form data.

This crate provides KVPairs, an ordered collection of key-value pairs, whose values can be either borrowed or owned, that can be used as HTTP query strings or form bodies. The kv_pairs! macro can be used to build KVPairs instances with a literal-like syntax.

KVPairs accepts values that implement IntoValue, this includes most primitive and standard library types like &str, String, bool, and common integer types. The impl_into_value_by_* macros can be used to implement IntoValue for more types.

KVPairs also accepts values that implement IntoValues, to insert 0, 1, or more values for a single key. This is useful for optional or multi-value parameters. The keys are NEVER automatically suffixed with [] when inserting values via IntoValues.

§Examples

Basic usage with the macro:

use kv_pairs::{kv_pairs, KVPairs};

let params = kv_pairs![
    "mode" => "day",
    "page" => 1_u32,
];
assert_eq!(params.content.len(), 2);

Optional parameters with Option (key omitted when None):

use kv_pairs::kv_pairs;

let p = kv_pairs![
    "q" => Some("search"),
    "filter" => None::<&str>,
];
assert_eq!(p.content.len(), 1);
assert_eq!(p.content[0], ("q", std::borrow::Cow::Borrowed("search")));

Multiple values for one key (e.g. tag=a&tag=b) via slice or array:

use kv_pairs::kv_pairs;

let p = kv_pairs!["tag" => ["a", "b"].as_slice()];
assert_eq!(p.content.len(), 2);
assert_eq!(p.content[0].0, "tag"); // No auto-suffixed `[]` for slice values
assert_eq!(p.content[0].1.as_ref(), "a");
assert_eq!(p.content[1].1.as_ref(), "b");

let p2 = kv_pairs!["x" => ["one", "two"]];
assert_eq!(p2.content.len(), 2);

Building programmatically with push and push_one:

use kv_pairs::KVPairs;

let mut p = KVPairs::new();
p.push_one("k", "v");
p.push("opt", Some(42_u32));
p.push("tags", ["a", "b"].as_slice());
assert_eq!(p.content.len(), 4);

Macros§

impl_into_value_by_as_ref_str
Implements IntoValue for types that yield &str via AsRef<str> (borrowed, no allocation).
impl_into_value_by_into_str_ref
Implements IntoValue for types that implement Into<&'a str> (borrowed; useful for enums).
impl_into_value_by_to_string
Implements IntoValue for types that implement ToString (owned, allocates).
kv_pairs
Builds KVPairs with literal-like syntax.

Structs§

KVPairs
A list of key-value pairs for API query or form parameters.

Traits§

IntoValue
Converts a value into Cow<'a, str> for use with KVPairs::push_one.
IntoValues
Yields an iterator of Cow<'a, str> for use with KVPairs::push.

Type Aliases§

KVPair
Type alias for the inner pair type.