next_web_ai/util/
key_values.rs

1use std::cmp::Ordering;
2
3use super::key_value::KeyValue;
4
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub struct KeyValues<T> {
7    sorted_set: Vec<T>,
8}
9
10impl<T> KeyValues<T>
11where
12    T: AsRef<dyn KeyValue>,
13    // T: std::cmp::PartialEq,
14{
15    /// Creates an empty KeyValues instance
16    pub fn empty() -> Self {
17        KeyValues {
18            sorted_set: Vec::with_capacity(0),
19        }
20    }
21
22    // /// Creates a KeyValues from a single key-value pair
23    // pub fn from_kv(key: String, value: String) -> Self {
24    //     KeyValues {
25    //         sorted_set: vec![KeyValue::new(key, value)],
26    //     }
27    // }
28
29    // /// Creates a KeyValues from an array of key-value pairs
30    // pub fn from_array(kvs: &[T]) -> Self {
31    //     let mut sorted = kvs.to_vec();
32    //     sorted.sort();
33    //     sorted.dedup_by(|a, b| a.key() == b.key());
34    //     KeyValues { sorted_set: sorted }
35    // }
36
37    /// Creates a KeyValues from key-value pairs in a vector
38    // pub fn from_vec(kvs: Vec<T>) -> Self {
39    //     let mut sorted = kvs;
40    //     sorted.sort();
41    //     sorted.dedup_by(|a, b| a.key() == b.key());
42    //     KeyValues { sorted_set: sorted }
43    // }
44
45    // /// Creates a KeyValues from an iterator of key-value pairs
46    // pub fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
47    //     let mut sorted: Vec<T> = iter.into_iter().collect();
48    //     sorted.sort();
49    //     sorted.dedup_by(|a, b| a.key() == b.key());
50    //     KeyValues { sorted_set: sorted }
51    // }
52
53    // /// Creates a KeyValues from string pairs (key1, value1, key2, value2, ...)
54    // pub fn from_str_pairs(pairs: &[&str]) -> Result<Self, &'static str> {
55    //     if pairs.len() % 2 != 0 {
56    //         return Err("Number of elements must be even (key-value pairs)");
57    //     }
58
59    //     let kvs: Vec<T> = pairs
60    //         .chunks(2)
61    //         .map(|chunk| T::new(chunk[0].to_string(), chunk[1].to_string()))
62    //         .collect();
63
64    //     Ok(Self::from_vec(kvs))
65    // }
66
67    /// Merges this KeyValues with another
68    pub fn and(self, other: Self) -> Self {
69        if other.sorted_set.is_empty() {
70            return self;
71        }
72
73        // if self == other {
74        //     return self;
75        // }
76
77        if self.sorted_set.is_empty() {
78            return other;
79        }
80
81        let mut merged = Vec::with_capacity(self.sorted_set.len() + other.sorted_set.len());
82        let mut self_iter = self.sorted_set.into_iter();
83        let mut other_iter = other.sorted_set.into_iter();
84
85        let mut self_next = self_iter.next();
86        let mut other_next = other_iter.next();
87
88        loop {
89            match (self_next.take(), other_next.take()) {
90                (Some(self_kv), Some(other_kv)) => {
91                    match self_kv.as_ref().key().cmp(&other_kv.as_ref().key()) {
92                        Ordering::Less => {
93                            merged.push(self_kv);
94                            self_next = self_iter.next();
95                            other_next = Some(other_kv);
96                        }
97                        Ordering::Greater => {
98                            merged.push(other_kv);
99                            self_next = Some(self_kv);
100                            other_next = other_iter.next();
101                        }
102                        Ordering::Equal => {
103                            // On conflict, prefer the other's value
104                            merged.push(other_kv);
105                            self_next = self_iter.next();
106                            other_next = other_iter.next();
107                        }
108                    }
109                }
110                (Some(self_kv), None) => {
111                    merged.push(self_kv);
112                    merged.extend(self_iter);
113                    break;
114                }
115                (None, Some(other_kv)) => {
116                    merged.push(other_kv);
117                    merged.extend(other_iter);
118                    break;
119                }
120                (None, None) => break,
121            }
122        }
123
124        KeyValues { sorted_set: merged }
125    }
126
127    /// Returns an iterator over the key-value pairs
128    pub fn iter(&self) -> impl Iterator<Item = &T> {
129        self.sorted_set.iter()
130    }
131
132    /// Returns the number of key-value pairs
133    pub fn len(&self) -> usize {
134        self.sorted_set.len()
135    }
136
137    /// Checks if the collection is empty
138    pub fn is_empty(&self) -> bool {
139        self.sorted_set.is_empty()
140    }
141}
142
143impl<'a, T> IntoIterator for &'a KeyValues<T>
144where
145    T: KeyValue,
146{
147    type Item = &'a T;
148    type IntoIter = std::slice::Iter<'a, T>;
149
150    fn into_iter(self) -> Self::IntoIter {
151        self.sorted_set.iter()
152    }
153}
154
155impl<T> IntoIterator for KeyValues<T>
156where
157    T: KeyValue,
158{
159    type Item = T;
160    type IntoIter = std::vec::IntoIter<T>;
161
162    fn into_iter(self) -> Self::IntoIter {
163        self.sorted_set.into_iter()
164    }
165}
166
167impl<T> std::fmt::Display for KeyValues<T>
168where
169    T: KeyValue,
170{
171    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
172        let s = self
173            .sorted_set
174            .iter()
175            .map(|kv| format!("{}={}", kv.key(), kv.value()))
176            .collect::<Vec<_>>()
177            .join(",");
178        write!(f, "[{}]", s)
179    }
180}