dfir_lang/graph/ops/
sort_by_key.rs

1use quote::quote_spanned;
2
3use super::{
4    DelayType, OperatorCategory, OperatorConstraints, OperatorWriteOutput, RANGE_0, RANGE_1,
5    WriteContextArgs,
6};
7
8/// Like sort, takes a stream as input and produces a version of the stream as output.
9/// This operator sorts according to the key extracted by the closure.
10///
11/// > Note: The closure has access to the [`context` object](surface_flows.mdx#the-context-object).
12///
13/// ```dfir
14/// source_iter(vec![(2, 'y'), (3, 'x'), (1, 'z')])
15///     -> sort_by_key(|(k, _v)| k)
16///     -> assert_eq([(1, 'z'), (2, 'y'), (3, 'x')]);
17/// ```
18pub const SORT_BY_KEY: OperatorConstraints = OperatorConstraints {
19    name: "sort_by_key",
20    categories: &[OperatorCategory::Persistence],
21    hard_range_inn: RANGE_1,
22    soft_range_inn: RANGE_1,
23    hard_range_out: RANGE_1,
24    soft_range_out: RANGE_1,
25    num_args: 1,
26    persistence_args: RANGE_0,
27    type_args: RANGE_0,
28    is_external_input: false,
29    has_singleton_output: false,
30    flo_type: None,
31    ports_inn: None,
32    ports_out: None,
33    input_delaytype_fn: |_| Some(DelayType::Stratum),
34    write_fn: |&WriteContextArgs {
35                   root,
36                   op_span,
37                   ident,
38                   inputs,
39                   is_pull,
40                   arguments,
41                   work_fn,
42                   ..
43               },
44               _| {
45        assert!(is_pull);
46        let input = &inputs[0];
47        let write_iterator = quote_spanned! {op_span=>
48            let #ident = #work_fn(|| {
49                let mut tmp = #input.collect::<Vec<_>>();
50                #root::util::sort_unstable_by_key_hrtb(&mut tmp, #arguments);
51                tmp
52            }).into_iter();
53        };
54        Ok(OperatorWriteOutput {
55            write_iterator,
56            ..Default::default()
57        })
58    },
59};