Skip to main content

nemo_plugin/
value.rs

1//! Value helpers for creating PluginValue instances
2
3use indexmap::IndexMap;
4use nemo_plugin_api::PluginValue;
5
6/// Helper trait for types that can be converted to PluginValue
7pub trait IntoPluginValue {
8    fn into_plugin_value(self) -> PluginValue;
9}
10
11impl IntoPluginValue for PluginValue {
12    fn into_plugin_value(self) -> PluginValue {
13        self
14    }
15}
16
17impl IntoPluginValue for &str {
18    fn into_plugin_value(self) -> PluginValue {
19        PluginValue::String(self.to_string())
20    }
21}
22
23impl IntoPluginValue for String {
24    fn into_plugin_value(self) -> PluginValue {
25        PluginValue::String(self)
26    }
27}
28
29impl IntoPluginValue for i64 {
30    fn into_plugin_value(self) -> PluginValue {
31        PluginValue::Integer(self)
32    }
33}
34
35impl IntoPluginValue for i32 {
36    fn into_plugin_value(self) -> PluginValue {
37        PluginValue::Integer(self as i64)
38    }
39}
40
41impl IntoPluginValue for f64 {
42    fn into_plugin_value(self) -> PluginValue {
43        PluginValue::Float(self)
44    }
45}
46
47impl IntoPluginValue for bool {
48    fn into_plugin_value(self) -> PluginValue {
49        PluginValue::Bool(self)
50    }
51}
52
53impl<T: IntoPluginValue> IntoPluginValue for Vec<T> {
54    fn into_plugin_value(self) -> PluginValue {
55        PluginValue::Array(self.into_iter().map(|v| v.into_plugin_value()).collect())
56    }
57}
58
59/// Creates a PluginValue::String
60pub fn str_value(s: impl Into<String>) -> PluginValue {
61    PluginValue::String(s.into())
62}
63
64/// Creates a PluginValue::Integer
65pub fn int_value(i: impl Into<i64>) -> PluginValue {
66    PluginValue::Integer(i.into())
67}
68
69/// Creates a PluginValue::Float
70pub fn float_value(f: impl Into<f64>) -> PluginValue {
71    PluginValue::Float(f.into())
72}
73
74/// Creates a PluginValue::Bool
75pub fn bool_value(b: bool) -> PluginValue {
76    PluginValue::Bool(b)
77}
78
79/// Creates a PluginValue::Array
80pub fn array_value<T: IntoPluginValue>(items: Vec<T>) -> PluginValue {
81    PluginValue::Array(items.into_iter().map(|v| v.into_plugin_value()).collect())
82}
83
84/// Creates a PluginValue::Object from key-value pairs
85pub fn object_value(pairs: &[(&str, PluginValue)]) -> PluginValue {
86    let mut map = IndexMap::new();
87    for (k, v) in pairs {
88        map.insert(k.to_string(), v.clone());
89    }
90    PluginValue::Object(map)
91}