risingwave_stream/executor/join/
join_row_set.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// Copyright 2024 RisingWave Labs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::borrow::Borrow;
use std::collections::btree_map::OccupiedError as BTreeMapOccupiedError;
use std::collections::BTreeMap;
use std::fmt::Debug;
use std::mem;
use std::ops::{Bound, RangeBounds};

use auto_enums::auto_enum;
use enum_as_inner::EnumAsInner;

const MAX_VEC_SIZE: usize = 4;

#[derive(Debug, EnumAsInner)]
pub enum JoinRowSet<K, V> {
    BTree(BTreeMap<K, V>),
    Vec(Vec<(K, V)>),
}

impl<K, V> Default for JoinRowSet<K, V> {
    fn default() -> Self {
        Self::Vec(Vec::new())
    }
}

#[derive(Debug)]
#[allow(dead_code)]
pub struct VecOccupiedError<'a, K, V> {
    key: &'a K,
    old_value: &'a V,
    new_value: V,
}

#[derive(Debug)]
pub enum JoinRowSetOccupiedError<'a, K: Ord, V> {
    BTree(BTreeMapOccupiedError<'a, K, V>),
    Vec(VecOccupiedError<'a, K, V>),
}

impl<K: Ord, V> JoinRowSet<K, V> {
    pub fn try_insert(
        &mut self,
        key: K,
        value: V,
    ) -> Result<&'_ mut V, JoinRowSetOccupiedError<'_, K, V>> {
        if let Self::Vec(inner) = self
            && inner.len() >= MAX_VEC_SIZE
        {
            let btree = BTreeMap::from_iter(inner.drain(..));
            mem::swap(self, &mut Self::BTree(btree));
        }

        match self {
            Self::BTree(inner) => inner
                .try_insert(key, value)
                .map_err(JoinRowSetOccupiedError::BTree),
            Self::Vec(inner) => {
                if let Some(pos) = inner.iter().position(|elem| elem.0 == key) {
                    Err(JoinRowSetOccupiedError::Vec(VecOccupiedError {
                        key: &inner[pos].0,
                        old_value: &inner[pos].1,
                        new_value: value,
                    }))
                } else {
                    if inner.capacity() == 0 {
                        // `Vec` will give capacity 4 when `1 < mem::size_of::<T> <= 1024`
                        // We only give one for memory optimization
                        inner.reserve_exact(1);
                    }
                    inner.push((key, value));
                    Ok(&mut inner.last_mut().unwrap().1)
                }
            }
        }
    }

    pub fn remove(&mut self, key: &K) -> Option<V> {
        let ret = match self {
            Self::BTree(inner) => inner.remove(key),
            Self::Vec(inner) => inner
                .iter()
                .position(|elem| &elem.0 == key)
                .map(|pos| inner.swap_remove(pos).1),
        };
        if let Self::BTree(inner) = self
            && inner.len() <= MAX_VEC_SIZE / 2
        {
            let btree = mem::take(inner);
            let vec = Vec::from_iter(btree);
            mem::swap(self, &mut Self::Vec(vec));
        }
        ret
    }

    pub fn len(&self) -> usize {
        match self {
            Self::BTree(inner) => inner.len(),
            Self::Vec(inner) => inner.len(),
        }
    }

    pub fn is_empty(&self) -> bool {
        match self {
            Self::BTree(inner) => inner.is_empty(),
            Self::Vec(inner) => inner.is_empty(),
        }
    }

    #[auto_enum(Iterator)]
    pub fn values_mut(&mut self) -> impl Iterator<Item = &'_ mut V> {
        match self {
            Self::BTree(inner) => inner.values_mut(),
            Self::Vec(inner) => inner.iter_mut().map(|(_, v)| v),
        }
    }

    #[auto_enum(Iterator)]
    pub fn keys(&self) -> impl Iterator<Item = &K> {
        match self {
            Self::BTree(inner) => inner.keys(),
            Self::Vec(inner) => inner.iter().map(|(k, _v)| k),
        }
    }

    #[auto_enum(Iterator)]
    pub fn range<T, R>(&self, range: R) -> impl Iterator<Item = (&K, &V)>
    where
        T: Ord + ?Sized,
        K: Borrow<T> + Ord,
        R: RangeBounds<T>,
    {
        match self {
            Self::BTree(inner) => inner.range(range),
            Self::Vec(inner) => inner
                .iter()
                .filter(move |(k, _)| range.contains(k.borrow()))
                .map(|(k, v)| (k, v)),
        }
    }

    pub fn lower_bound_key(&self, bound: Bound<&K>) -> Option<&K> {
        self.lower_bound(bound).map(|(k, _v)| k)
    }

    pub fn upper_bound_key(&self, bound: Bound<&K>) -> Option<&K> {
        self.upper_bound(bound).map(|(k, _v)| k)
    }

    pub fn lower_bound(&self, bound: Bound<&K>) -> Option<(&K, &V)> {
        match self {
            Self::BTree(inner) => inner.lower_bound(bound).next(),
            Self::Vec(inner) => inner
                .iter()
                .filter(|(k, _)| (bound, Bound::Unbounded).contains(k))
                .min_by_key(|(k, _)| k)
                .map(|(k, v)| (k, v)),
        }
    }

    pub fn upper_bound(&self, bound: Bound<&K>) -> Option<(&K, &V)> {
        match self {
            Self::BTree(inner) => inner.upper_bound(bound).prev(),
            Self::Vec(inner) => inner
                .iter()
                .filter(|(k, _)| (Bound::Unbounded, bound).contains(k))
                .max_by_key(|(k, _)| k)
                .map(|(k, v)| (k, v)),
        }
    }

    pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
        match self {
            Self::BTree(inner) => inner.get_mut(key),
            Self::Vec(inner) => inner.iter_mut().find(|(k, _)| k == key).map(|(_, v)| v),
        }
    }

    pub fn get(&self, key: &K) -> Option<&V> {
        match self {
            Self::BTree(inner) => inner.get(key),
            Self::Vec(inner) => inner.iter().find(|(k, _)| k == key).map(|(_, v)| v),
        }
    }

    /// Returns the key-value pair with smallest key in the map.
    pub fn first_key_sorted(&self) -> Option<&K> {
        match self {
            Self::BTree(inner) => inner.first_key_value().map(|(k, _)| k),
            Self::Vec(inner) => inner.iter().map(|(k, _)| k).min(),
        }
    }

    /// Returns the key-value pair with the second smallest key in the map.
    pub fn second_key_sorted(&self) -> Option<&K> {
        match self {
            Self::BTree(inner) => inner.iter().nth(1).map(|(k, _)| k),
            Self::Vec(inner) => {
                let mut res = None;
                let mut smallest = None;
                for (k, _) in inner {
                    if let Some(smallest_k) = smallest {
                        if k < smallest_k {
                            res = Some(smallest_k);
                            smallest = Some(k);
                        } else if let Some(res_k) = res {
                            if k < res_k {
                                res = Some(k);
                            }
                        } else {
                            res = Some(k);
                        }
                    } else {
                        smallest = Some(k);
                    }
                }
                res
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_join_row_set_bounds() {
        let mut join_row_set: JoinRowSet<i32, i32> = JoinRowSet::default();

        // Insert elements
        assert!(join_row_set.try_insert(1, 10).is_ok());
        assert!(join_row_set.try_insert(2, 20).is_ok());
        assert!(join_row_set.try_insert(3, 30).is_ok());

        // Check lower bound
        assert_eq!(join_row_set.lower_bound_key(Bound::Included(&2)), Some(&2));
        assert_eq!(join_row_set.lower_bound_key(Bound::Excluded(&2)), Some(&3));

        // Check upper bound
        assert_eq!(join_row_set.upper_bound_key(Bound::Included(&2)), Some(&2));
        assert_eq!(join_row_set.upper_bound_key(Bound::Excluded(&2)), Some(&1));
    }

    #[test]
    fn test_join_row_set_first_and_second_key_sorted() {
        {
            let mut join_row_set: JoinRowSet<i32, i32> = JoinRowSet::default();

            // Insert elements
            assert!(join_row_set.try_insert(3, 30).is_ok());
            assert!(join_row_set.try_insert(1, 10).is_ok());
            assert!(join_row_set.try_insert(2, 20).is_ok());

            // Check first key sorted
            assert_eq!(join_row_set.first_key_sorted(), Some(&1));

            // Check second key sorted
            assert_eq!(join_row_set.second_key_sorted(), Some(&2));
        }
        {
            let mut join_row_set: JoinRowSet<i32, i32> = JoinRowSet::default();

            // Insert elements
            assert!(join_row_set.try_insert(1, 10).is_ok());
            assert!(join_row_set.try_insert(2, 20).is_ok());

            // Check first key sorted
            assert_eq!(join_row_set.first_key_sorted(), Some(&1));

            // Check second key sorted
            assert_eq!(join_row_set.second_key_sorted(), Some(&2));
        }
    }
}