keyring_core/
attributes.rs

1/*!
2
3Utility functions for attribute maps
4
5 */
6use std::collections::HashMap;
7
8use crate::{Error::Invalid, Result};
9
10/// Parse an optional key-value &str map for allowed keys, returning a map of owned strings.
11///
12/// Returns an [Invalid] error if not all keys are allowed.
13pub fn parse_attributes(
14    keys: &[&str],
15    attrs: Option<&HashMap<&str, &str>>,
16) -> Result<HashMap<String, String>> {
17    let mut result: HashMap<String, String> = HashMap::new();
18    if attrs.is_none() {
19        return Ok(result);
20    }
21    for (key, value) in attrs.unwrap() {
22        if keys.contains(key) {
23            result.insert(key.to_string(), value.to_string());
24        } else {
25            return Err(Invalid(key.to_string(), "unknown key".to_string()));
26        }
27    }
28    Ok(result)
29}
30
31/// Convert a borrowed key-value map of borrowed strings to an owned map of owned strings.
32pub fn externalize_attributes(attrs: &HashMap<&str, &str>) -> HashMap<String, String> {
33    attrs
34        .iter()
35        .map(|(k, v)| (k.to_string(), v.to_string()))
36        .collect()
37}