use super::DownloadOptions;
use crate::config::OptionRegistry;
pub fn option_value_to_string(value: &serde_json::Value) -> Option<String> {
match value {
serde_json::Value::String(value) => Some(value.clone()),
serde_json::Value::Number(value) => Some(value.to_string()),
serde_json::Value::Bool(value) => Some(value.to_string()),
serde_json::Value::Array(values) => values
.iter()
.map(option_value_to_string)
.collect::<Option<Vec<_>>>()
.map(|values| values.join("\n")),
serde_json::Value::Null | serde_json::Value::Object(_) => None,
}
}
impl DownloadOptions {
pub fn from_option_values(
options: &std::collections::HashMap<String, crate::config::OptionValue>,
) -> Self {
let string_options = options
.iter()
.filter(|(_, value)| !value.is_none())
.map(|(key, value)| (key.clone(), value.to_string()))
.collect();
Self::from_option_strings(&string_options)
}
pub fn from_rpc_options(
options: &std::collections::HashMap<String, serde_json::Value>,
) -> Self {
Self::try_from_rpc_options(options).unwrap_or_default()
}
pub fn try_from_rpc_options(
options: &std::collections::HashMap<String, serde_json::Value>,
) -> Result<Self, String> {
let registry = crate::config::OptionRegistry::new();
let mut string_options = std::collections::HashMap::with_capacity(options.len());
for (key, value) in options {
if registry.get(key).is_none() {
continue;
}
registry
.parse_rpc_value(key, value)
.map_err(|error| format!("Option '{}': {}", key, error))?;
let value = option_value_to_string(value)
.ok_or_else(|| format!("Option '{}' must be a string", key))?;
string_options.insert(OptionRegistry::canonical_name(key).to_string(), value);
}
Ok(Self::from_option_strings(&string_options))
}
}