vector_config/external/
indexmap.rs

1use std::cell::RefCell;
2
3use indexmap::{IndexMap, IndexSet};
4use serde_json::Value;
5
6use crate::{
7    Configurable, GenerateError, Metadata, ToValue,
8    schema::{
9        SchemaGenerator, SchemaObject, assert_string_schema_for_map, generate_map_schema,
10        generate_set_schema,
11    },
12    str::ConfigurableString,
13};
14
15impl<K, V> Configurable for IndexMap<K, V>
16where
17    K: ConfigurableString + ToValue + std::hash::Hash + Eq + 'static,
18    V: Configurable + ToValue + 'static,
19{
20    fn is_optional() -> bool {
21        // A hashmap with required fields would be... an object.  So if you want that, make a struct
22        // instead, not a hashmap.
23        true
24    }
25
26    fn metadata() -> Metadata {
27        Metadata::with_transparent(true)
28    }
29
30    fn validate_metadata(metadata: &Metadata) -> Result<(), GenerateError> {
31        let converted = metadata.convert();
32        V::validate_metadata(&converted)
33    }
34
35    fn generate_schema(
36        generator: &RefCell<SchemaGenerator>,
37    ) -> Result<SchemaObject, GenerateError> {
38        // Make sure our key type is _truly_ a string schema.
39        assert_string_schema_for_map(
40            &K::as_configurable_ref(),
41            generator,
42            std::any::type_name::<Self>(),
43        )?;
44
45        generate_map_schema(&V::as_configurable_ref(), generator)
46    }
47}
48
49impl<K, V> ToValue for IndexMap<K, V>
50where
51    K: ToString,
52    V: ToValue,
53{
54    fn to_value(&self) -> Value {
55        Value::Object(
56            self.iter()
57                .map(|(k, v)| (k.to_string(), v.to_value()))
58                .collect(),
59        )
60    }
61}
62
63impl<V> Configurable for IndexSet<V>
64where
65    V: Configurable + ToValue + std::hash::Hash + Eq + 'static,
66{
67    fn metadata() -> Metadata {
68        Metadata::with_transparent(true)
69    }
70
71    fn validate_metadata(metadata: &Metadata) -> Result<(), GenerateError> {
72        let converted = metadata.convert();
73        V::validate_metadata(&converted)
74    }
75
76    fn generate_schema(
77        generator: &RefCell<SchemaGenerator>,
78    ) -> Result<SchemaObject, GenerateError> {
79        generate_set_schema(&V::as_configurable_ref(), generator)
80    }
81}
82
83impl<V: ToValue> ToValue for IndexSet<V> {
84    fn to_value(&self) -> Value {
85        Value::Array(self.iter().map(ToValue::to_value).collect())
86    }
87}