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
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
    record, Category, Example, IntoInterruptiblePipelineData, PipelineData, ShellError, Signature,
    Type, Value,
};

#[derive(Clone)]
pub struct Enumerate;

impl Command for Enumerate {
    fn name(&self) -> &str {
        "enumerate"
    }

    fn usage(&self) -> &str {
        "Enumerate the elements in a stream."
    }

    fn search_terms(&self) -> Vec<&str> {
        vec!["itemize"]
    }

    fn signature(&self) -> nu_protocol::Signature {
        Signature::build("enumerate")
            .input_output_types(vec![(Type::Any, Type::Table(vec![]))])
            .category(Category::Filters)
    }

    fn examples(&self) -> Vec<Example> {
        vec![Example {
            description: "Add an index to each element of a list",
            example: r#"[a, b, c] | enumerate "#,
            result: Some(Value::test_list(vec![
                Value::test_record(record! {
                    "index" =>  Value::test_int(0),
                    "item" =>   Value::test_string("a"),
                }),
                Value::test_record(record! {
                    "index" =>  Value::test_int(1),
                    "item" =>   Value::test_string("b"),
                }),
                Value::test_record(record! {
                    "index" =>  Value::test_int(2),
                    "item" =>   Value::test_string("c"),
                }),
            ])),
        }]
    }

    fn run(
        &self,
        engine_state: &EngineState,
        _stack: &mut Stack,
        call: &Call,
        input: PipelineData,
    ) -> Result<PipelineData, ShellError> {
        let metadata = input.metadata();
        let ctrlc = engine_state.ctrlc.clone();
        let span = call.head;

        Ok(input
            .into_iter()
            .enumerate()
            .map(move |(idx, x)| {
                Value::record(
                    record! {
                        "index" => Value::int(idx as i64, span),
                        "item" => x,
                    },
                    span,
                )
            })
            .into_pipeline_data_with_metadata(metadata, ctrlc))
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_examples() {
        use crate::test_examples;

        test_examples(Enumerate {})
    }
}