nu_command/filters/
last.rs

1use nu_engine::command_prelude::*;
2use nu_protocol::shell_error::io::IoError;
3use std::{collections::VecDeque, io::Read};
4
5#[derive(Clone)]
6pub struct Last;
7
8impl Command for Last {
9    fn name(&self) -> &str {
10        "last"
11    }
12
13    fn signature(&self) -> Signature {
14        Signature::build("last")
15            .input_output_types(vec![
16                (
17                    // TODO: This is too permissive; if we could express this
18                    // using a type parameter it would be List<T> -> T.
19                    Type::List(Box::new(Type::Any)),
20                    Type::Any,
21                ),
22                (Type::Binary, Type::Binary),
23                (Type::Range, Type::Any),
24            ])
25            .optional(
26                "rows",
27                SyntaxShape::Int,
28                "Starting from the back, the number of rows to return.",
29            )
30            .category(Category::Filters)
31    }
32
33    fn description(&self) -> &str {
34        "Return only the last several rows of the input. Counterpart of `first`. Opposite of `drop`."
35    }
36
37    fn examples(&self) -> Vec<Example<'_>> {
38        vec![
39            Example {
40                example: "[1,2,3] | last 2",
41                description: "Return the last 2 items of a list/table",
42                result: Some(Value::list(
43                    vec![Value::test_int(2), Value::test_int(3)],
44                    Span::test_data(),
45                )),
46            },
47            Example {
48                example: "[1,2,3] | last",
49                description: "Return the last item of a list/table",
50                result: Some(Value::test_int(3)),
51            },
52            Example {
53                example: "0x[01 23 45] | last 2",
54                description: "Return the last 2 bytes of a binary value",
55                result: Some(Value::binary(vec![0x23, 0x45], Span::test_data())),
56            },
57            Example {
58                example: "1..3 | last",
59                description: "Return the last item of a range",
60                result: Some(Value::test_int(3)),
61            },
62        ]
63    }
64
65    fn run(
66        &self,
67        engine_state: &EngineState,
68        stack: &mut Stack,
69        call: &Call,
70        input: PipelineData,
71    ) -> Result<PipelineData, ShellError> {
72        let head = call.head;
73        let rows: Option<Spanned<i64>> = call.opt(engine_state, stack, 0)?;
74
75        // FIXME: Please read the FIXME message in `first.rs`'s `first_helper` implementation.
76        // It has the same issue.
77        let return_single_element = rows.is_none();
78        let rows = if let Some(rows) = rows {
79            if rows.item < 0 {
80                return Err(ShellError::NeedsPositiveValue { span: rows.span });
81            } else {
82                rows.item as usize
83            }
84        } else {
85            1
86        };
87
88        let metadata = input.metadata();
89
90        // early exit for `last 0`
91        if rows == 0 {
92            return Ok(Value::list(Vec::new(), head).into_pipeline_data_with_metadata(metadata));
93        }
94
95        match input {
96            PipelineData::ListStream(_, _) | PipelineData::Value(Value::Range { .. }, _) => {
97                let iterator = input.into_iter_strict(head)?;
98
99                // only keep the last `rows` in memory
100                let mut buf = VecDeque::new();
101
102                for row in iterator {
103                    engine_state.signals().check(&head)?;
104                    if buf.len() == rows {
105                        buf.pop_front();
106                    }
107                    buf.push_back(row);
108                }
109
110                if return_single_element {
111                    if let Some(last) = buf.pop_back() {
112                        Ok(last.into_pipeline_data())
113                    } else {
114                        Err(ShellError::AccessEmptyContent { span: head })
115                    }
116                } else {
117                    Ok(Value::list(buf.into(), head).into_pipeline_data_with_metadata(metadata))
118                }
119            }
120            PipelineData::Value(val, _) => {
121                let span = val.span();
122                match val {
123                    Value::List { mut vals, .. } => {
124                        if return_single_element {
125                            if let Some(v) = vals.pop() {
126                                Ok(v.into_pipeline_data())
127                            } else {
128                                Err(ShellError::AccessEmptyContent { span: head })
129                            }
130                        } else {
131                            let i = vals.len().saturating_sub(rows);
132                            vals.drain(..i);
133                            Ok(Value::list(vals, span).into_pipeline_data_with_metadata(metadata))
134                        }
135                    }
136                    Value::Binary { mut val, .. } => {
137                        if return_single_element {
138                            if let Some(val) = val.pop() {
139                                Ok(Value::int(val.into(), span).into_pipeline_data())
140                            } else {
141                                Err(ShellError::AccessEmptyContent { span: head })
142                            }
143                        } else {
144                            let i = val.len().saturating_sub(rows);
145                            val.drain(..i);
146                            Ok(Value::binary(val, span).into_pipeline_data())
147                        }
148                    }
149                    // Propagate errors by explicitly matching them before the final case.
150                    Value::Error { error, .. } => Err(*error),
151                    other => Err(ShellError::OnlySupportsThisInputType {
152                        exp_input_type: "list, binary or range".into(),
153                        wrong_type: other.get_type().to_string(),
154                        dst_span: head,
155                        src_span: other.span(),
156                    }),
157                }
158            }
159            PipelineData::ByteStream(stream, ..) => {
160                if stream.type_().is_binary_coercible() {
161                    let span = stream.span();
162                    if let Some(mut reader) = stream.reader() {
163                        // Have to be a bit tricky here, but just consume into a VecDeque that we
164                        // shrink to fit each time
165                        const TAKE: u64 = 8192;
166                        let mut buf = VecDeque::with_capacity(rows + TAKE as usize);
167                        loop {
168                            let taken = std::io::copy(&mut (&mut reader).take(TAKE), &mut buf)
169                                .map_err(|err| IoError::new(err, span, None))?;
170                            if buf.len() > rows {
171                                buf.drain(..(buf.len() - rows));
172                            }
173                            if taken < TAKE {
174                                // This must be EOF.
175                                if return_single_element {
176                                    if !buf.is_empty() {
177                                        return Ok(
178                                            Value::int(buf[0] as i64, head).into_pipeline_data()
179                                        );
180                                    } else {
181                                        return Err(ShellError::AccessEmptyContent { span: head });
182                                    }
183                                } else {
184                                    return Ok(Value::binary(buf, head).into_pipeline_data());
185                                }
186                            }
187                        }
188                    } else {
189                        Ok(PipelineData::empty())
190                    }
191                } else {
192                    Err(ShellError::OnlySupportsThisInputType {
193                        exp_input_type: "list, binary or range".into(),
194                        wrong_type: stream.type_().describe().into(),
195                        dst_span: head,
196                        src_span: stream.span(),
197                    })
198                }
199            }
200            PipelineData::Empty => Err(ShellError::OnlySupportsThisInputType {
201                exp_input_type: "list, binary or range".into(),
202                wrong_type: "null".into(),
203                dst_span: call.head,
204                src_span: call.head,
205            }),
206        }
207    }
208}
209
210#[cfg(test)]
211mod test {
212    use super::*;
213
214    #[test]
215    fn test_examples() {
216        use crate::test_examples;
217
218        test_examples(Last {})
219    }
220}