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