zrx_stream/stream/operator/
sort.rs

1// Copyright (c) 2025-2026 Zensical and contributors
2
3// SPDX-License-Identifier: MIT
4// All contributions are certified under the 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;
30
31use zrx_scheduler::action::descriptor::Property;
32use zrx_scheduler::action::output::IntoOutputs;
33use zrx_scheduler::action::Descriptor;
34use zrx_scheduler::effect::Item;
35use zrx_scheduler::{Id, Value};
36use zrx_store::decorator::Indexed;
37use zrx_store::Store;
38
39use crate::stream::value::Position;
40use crate::stream::Stream;
41
42use super::{Operator, OperatorExt};
43
44// ----------------------------------------------------------------------------
45// Structs
46// ----------------------------------------------------------------------------
47
48/// Sort operator.
49struct Sort<I, T>
50where
51    I: Id,
52{
53    /// Store of items.
54    store: Indexed<I, T>,
55}
56
57// ----------------------------------------------------------------------------
58// Implementations
59// ----------------------------------------------------------------------------
60
61impl<I, T> Stream<I, T>
62where
63    I: Id,
64    T: Value + Clone + Ord,
65{
66    pub fn sort(&self) -> Stream<I, Position<T>> {
67        self.with_operator(Sort { store: Indexed::default() })
68    }
69
70    pub fn sort_with<F>(&self, f: F) -> Stream<I, Position<T>>
71    where
72        F: Fn(&T, &T) -> Ordering + 'static,
73    {
74        self.with_operator(Sort { store: Indexed::with_order(f) })
75    }
76
77    pub fn sort_by<F, K>(&self, f: F) -> Stream<I, Position<T>>
78    where
79        F: Fn(&T) -> K + 'static,
80        K: Ord,
81    {
82        self.with_operator(Sort {
83            store: Indexed::with_order(move |a, b| f(a).cmp(&f(b))),
84        })
85    }
86}
87
88// ----------------------------------------------------------------------------
89// Trait implementations
90// ----------------------------------------------------------------------------
91
92impl<I, T> Operator<I, T> for Sort<I, T>
93where
94    I: Id,
95    T: Value + Clone + Ord,
96{
97    type Item<'a> = Item<&'a I, Option<&'a T>>;
98
99    /// Handles the given item.
100    ///
101    /// Sorting a stream involves maintaining an internal store of items, and
102    /// updating the positions of items whenever an item is inserted, updated,
103    /// or removed. The returned items are annotated with their new positions,
104    /// which reflect their order in the sorted stream.
105    #[cfg_attr(
106        feature = "tracing",
107        tracing::instrument(level = "debug", skip_all, fields(id = %item.id))
108    )]
109    fn handle(&mut self, item: Self::Item<'_>) -> impl IntoOutputs<I> {
110        let len = self.store.len();
111
112        // After determining the current length of the store, which we need to
113        // discern insertions from in-place updates, we either insert into or
114        // remove the item from the store, which gives us the affected range of
115        // indices. When the range is `None`, it means that nothing changed.
116        match item.data {
117            Some(data) => self.store.insert_if_changed(item.id, data),
118            None => self.store.remove(item.id).map(|n| n..n),
119        }
120        // If nothing changed, we can return early. Otherwise, if the number of
121        // items in the store changed, we must update the positions of all items
122        // that come after the affected range. In this case, we need to extend
123        // the range to cover the end of the store.
124        .map(|Range { start, mut end }| {
125            if len != self.store.len() {
126                end = self.store.len();
127            }
128
129            // If an item was deleted from the store, we need to include the
130            // deletion with all items that changed their positions
131            let mut items = Vec::with_capacity(end - start);
132            if len > self.store.len() {
133                items.push(Item::new(item.id.clone(), None));
134            }
135
136            // Now, we can iterate over the affected range and create new items
137            // with updated positions beginning at the start of the range
138            for (index, pair) in self.store.range(start..end).enumerate() {
139                let item = Item::from(pair).into_owned();
140                items.push(
141                    item.map(|data| Some(Position::new(start + index, data))),
142                );
143            }
144
145            // Return items
146            items
147        })
148        .unwrap_or_default()
149    }
150
151    /// Returns the descriptor.
152    #[inline]
153    fn descriptor(&self) -> Descriptor {
154        Descriptor::builder() // fmt
155            .property(Property::Flush)
156            .build()
157    }
158}