Skip to main content

nu_command/generators/
seq.rs

1use nu_engine::command_prelude::*;
2use nu_protocol::{ListStream, shell_error::generic::GenericError};
3
4#[derive(Clone)]
5pub struct Seq;
6
7impl Command for Seq {
8    fn name(&self) -> &str {
9        "seq"
10    }
11
12    fn signature(&self) -> Signature {
13        Signature::build("seq")
14            .input_output_types(vec![(Type::Nothing, Type::List(Box::new(Type::Number)))])
15            .rest("rest", SyntaxShape::Number, "Sequence values.")
16            .category(Category::Generators)
17    }
18
19    fn description(&self) -> &str {
20        "Output sequences of numbers."
21    }
22
23    fn run(
24        &self,
25        engine_state: &EngineState,
26        stack: &mut Stack,
27        call: &Call,
28        _input: PipelineData,
29    ) -> Result<PipelineData, ShellError> {
30        seq(engine_state, stack, call)
31    }
32
33    fn examples(&self) -> Vec<Example<'_>> {
34        vec![
35            Example {
36                description: "sequence 1 to 10",
37                example: "seq 1 10",
38                result: Some(Value::list(
39                    vec![
40                        Value::test_int(1),
41                        Value::test_int(2),
42                        Value::test_int(3),
43                        Value::test_int(4),
44                        Value::test_int(5),
45                        Value::test_int(6),
46                        Value::test_int(7),
47                        Value::test_int(8),
48                        Value::test_int(9),
49                        Value::test_int(10),
50                    ],
51                    Span::test_data(),
52                )),
53            },
54            Example {
55                description: "sequence 1.0 to 2.0 by 0.1s",
56                example: "seq 1.0 0.1 2.0",
57                result: Some(Value::list(
58                    vec![
59                        Value::test_float(1.0000),
60                        Value::test_float(1.1000),
61                        Value::test_float(1.2000),
62                        Value::test_float(1.3000),
63                        Value::test_float(1.4000),
64                        Value::test_float(1.5000),
65                        Value::test_float(1.6000),
66                        Value::test_float(1.7000),
67                        Value::test_float(1.8000),
68                        Value::test_float(1.9000),
69                        Value::test_float(2.0000),
70                    ],
71                    Span::test_data(),
72                )),
73            },
74            Example {
75                description: "sequence 1 to 5, then convert to a string with a pipe separator",
76                example: "seq 1 5 | str join '|'",
77                result: None,
78            },
79        ]
80    }
81}
82
83fn seq(
84    engine_state: &EngineState,
85    stack: &mut Stack,
86    call: &Call,
87) -> Result<PipelineData, ShellError> {
88    let span = call.head;
89    let rest_nums: Vec<Spanned<f64>> = call.rest(engine_state, stack, 0)?;
90
91    // note that the check for int or float has to occur here. prior, the check would occur after
92    // everything had been generated; this does not work well with ListStreams.
93    // As such, the simple test is to check if this errors out: that means there is a float in the
94    // input, which necessarily means that parts of the output will be floats.
95    let rest_nums_check: Result<Vec<Spanned<i64>>, ShellError> = call.rest(engine_state, stack, 0);
96    let contains_decimals = rest_nums_check.is_err();
97
98    if rest_nums.is_empty() {
99        return Err(ShellError::Generic(GenericError::new(
100            "seq requires some parameters",
101            "needs parameter",
102            call.head,
103        )));
104    }
105
106    // A zero increment never terminates (`seq 5 0 5` would emit `5` forever) or
107    // silently produces nothing, so reject it up front like GNU `seq` does.
108    // The increment is the middle argument; with fewer than three arguments it
109    // defaults to 1 and cannot be zero.
110    if rest_nums.len() > 2 && rest_nums[1].item == 0.0 {
111        return Err(ShellError::IncorrectValue {
112            msg: "increment cannot be 0".into(),
113            val_span: rest_nums[1].span,
114            call_span: span,
115        });
116    }
117
118    let rest_nums: Vec<f64> = rest_nums.iter().map(|n| n.item).collect();
119
120    run_seq(rest_nums, span, contains_decimals, engine_state)
121}
122
123pub fn run_seq(
124    free: Vec<f64>,
125    span: Span,
126    contains_decimals: bool,
127    engine_state: &EngineState,
128) -> Result<PipelineData, ShellError> {
129    let first = free[0];
130    let step = if free.len() > 2 { free[1] } else { 1.0 };
131    let last = { free[free.len() - 1] };
132
133    let stream = if !contains_decimals {
134        ListStream::new(
135            IntSeq {
136                count: Some(first as i64),
137                step: step as i64,
138                last: last as i64,
139                span,
140            },
141            span,
142            engine_state.signals().clone(),
143        )
144    } else {
145        ListStream::new(
146            FloatSeq {
147                first,
148                step,
149                last,
150                index: 0,
151                span,
152            },
153            span,
154            engine_state.signals().clone(),
155        )
156    };
157
158    Ok(stream.into())
159}
160
161struct FloatSeq {
162    first: f64,
163    step: f64,
164    last: f64,
165    index: isize,
166    span: Span,
167}
168
169impl Iterator for FloatSeq {
170    type Item = Value;
171    fn next(&mut self) -> Option<Value> {
172        let count = self.first + self.index as f64 * self.step;
173        // Accuracy guaranteed as far as possible; each time, the value is re-evaluated from the
174        // base arguments
175        if (count > self.last && self.step >= 0.0) || (count < self.last && self.step <= 0.0) {
176            return None;
177        }
178        self.index += 1;
179        Some(Value::float(count, self.span))
180    }
181}
182
183struct IntSeq {
184    count: Option<i64>,
185    step: i64,
186    last: i64,
187    span: Span,
188}
189
190impl Iterator for IntSeq {
191    type Item = Value;
192    fn next(&mut self) -> Option<Value> {
193        let count = self.count?;
194        if (count > self.last && self.step >= 0) || (count < self.last && self.step <= 0) {
195            self.count = None;
196            return None;
197        }
198        // None on overflow: emit this value, then end (avoids panic/wrap).
199        self.count = count.checked_add(self.step);
200        Some(Value::int(count, self.span))
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    #[test]
209    fn test_examples() -> nu_test_support::Result {
210        nu_test_support::test().examples(Seq)
211    }
212}