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
IntoValuefor types that yield&strviaAsRef<str>(borrowed, no allocation). - impl_
into_ value_ by_ into_ str_ ref - Implements
IntoValuefor types that implementInto<&'a str>(borrowed; useful for enums). - impl_
into_ value_ by_ to_ string - Implements
IntoValuefor types that implementToString(owned, allocates). - kv_
pairs - Builds
KVPairswith literal-like syntax.
Structs§
- KVPairs
- A list of key-value pairs for API query or form parameters.
Traits§
- Into
Value - Converts a value into
Cow<'a, str>for use withKVPairs::push_one. - Into
Values - Yields an iterator of
Cow<'a, str>for use withKVPairs::push.
Type Aliases§
- KVPair
- Type alias for the inner pair type.