zrx_stream/stream/operator/
sort.rs

1// Copyright (c) 2025 Zensical and contributors
2
3// SPDX-License-Identifier: MIT
4// Third-party contributions licensed under DCO
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to
8// deal in the Software without restriction, including without limitation the
9// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10// sell copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in
14// all copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22// IN THE SOFTWARE.
23
24// ----------------------------------------------------------------------------
25
26//! Sort operator.
27
28use std::cmp::Ordering;
29use std::ops::Range;
30use zrx_scheduler::action::descriptor::Property;
31use zrx_scheduler::action::output::IntoOutputs;
32use zrx_scheduler::action::Descriptor;
33use zrx_scheduler::effect::Item;
34use zrx_scheduler::{Id, Value};
35use zrx_store::decorator::Indexed;
36use zrx_store::Store;
37
38use crate::stream::value::Position;
39use crate::stream::Stream;
40
41use super::{Operator, OperatorExt};
42
43// ----------------------------------------------------------------------------
44// Structs
45// ----------------------------------------------------------------------------
46
47/// Sort operator.
48struct Sort<I, T>
49where
50    I: Id,
51{
52    /// Store of items.
53    store: Indexed<I, T>,
54}
55
56// ----------------------------------------------------------------------------
57// Implementations
58// ----------------------------------------------------------------------------
59
60impl<I, T> Stream<I, T>
61where
62    I: Id,
63    T: Value + Clone + Ord,
64{
65    pub fn sort(&self) -> Stream<I, Position<T>> {
66        self.with_operator(Sort { store: Indexed::default() })
67    }
68
69    pub fn sort_with<F>(&self, f: F) -> Stream<I, Position<T>>
70    where
71        F: Fn(&T, &T) -> Ordering + 'static,
72    {
73        self.with_operator(Sort { store: Indexed::with_order(f) })
74    }
75
76    pub fn sort_by<F, K>(&self, f: F) -> Stream<I, Position<T>>
77    where
78        F: Fn(&T) -> K + 'static,
79        K: Ord,
80    {
81        self.with_operator(Sort {
82            store: Indexed::with_order(move |a, b| f(a).cmp(&f(b))),
83        })
84    }
85}
86
87// ----------------------------------------------------------------------------
88// Trait implementations
89// ----------------------------------------------------------------------------
90
91impl<I, T> Operator<I, T> for Sort<I, T>
92where
93    I: Id,
94    T: Value + Clone + Ord,
95{
96    type Item<'a> = Item<&'a I, Option<&'a T>>;
97
98    /// Handles the given item.
99    ///
100    /// Sorting a stream involves maintaining an internal store of items, and
101    /// updating the positions of items whenever an item is inserted, updated,
102    /// or removed. The returned items are annotated with their new positions,
103    /// which reflect their order in the sorted stream.
104    #[cfg_attr(
105        feature = "tracing",
106        tracing::instrument(level = "debug", skip_all, fields(id = %item.id))
107    )]
108    fn handle(&mut self, item: Self::Item<'_>) -> impl IntoOutputs<I> {
109        let len = self.store.len();
110
111        // After determining the current length of the store, which we need to
112        // discern insertions from in-place updates, we either insert into or
113        // remove the item from the store, which gives us the affected range of
114        // indices. When the range is `None`, it means that nothing changed.
115        match item.data {
116            Some(data) => self.store.insert_if_changed(item.id, data),
117            None => self.store.remove(item.id).map(|n| n..n),
118        }
119        // If nothing changed, we can return early. Otherwise, if the number of
120        // items in the store changed, we must update the positions of all items
121        // that come after the affected range. In this case, we need to extend
122        // the range to cover the end of the store.
123        .map(|Range { start, mut end }| {
124            if len != self.store.len() {
125                end = self.store.len();
126            }
127
128            // If an item was deleted from the store, we need to include the
129            // deletion with all items that changed their positions
130            let mut items = Vec::with_capacity(end - start);
131            if len > self.store.len() {
132                items.push(Item::new(item.id.clone(), None));
133            }
134
135            // Now, we can iterate over the affected range and create new items
136            // with updated positions beginning at the start of the range
137            for (index, pair) in self.store.range(start..end).enumerate() {
138                let item = Item::from(pair).into_owned();
139                items.push(
140                    item.map(|data| Some(Position::new(start + index, data))),
141                );
142            }
143
144            // Return items
145            items
146        })
147        .unwrap_or_default()
148    }
149
150    /// Returns the descriptor.
151    #[inline]
152    fn descriptor(&self) -> Descriptor {
153        Descriptor::builder() // fmt
154            .property(Property::Flush)
155            .build()
156    }
157}