nu_command/filters/
length.rs1use std::io::Read;
2
3use nu_engine::command_prelude::*;
4
5#[derive(Clone)]
6pub struct Length;
7
8impl Command for Length {
9 fn name(&self) -> &str {
10 "length"
11 }
12
13 fn description(&self) -> &str {
14 "Count the number of items in an input list, rows in a table, or bytes in binary data."
15 }
16
17 fn signature(&self) -> nu_protocol::Signature {
18 Signature::build("length")
19 .input_output_types(vec![
20 (Type::List(Box::new(Type::Any)), Type::Int),
21 (Type::Binary, Type::Int),
22 (Type::Nothing, Type::Int),
23 ])
24 .category(Category::Filters)
25 }
26
27 fn search_terms(&self) -> Vec<&str> {
28 vec!["count", "size", "wc"]
29 }
30
31 fn run(
32 &self,
33 _engine_state: &EngineState,
34 _stack: &mut Stack,
35 call: &Call,
36 input: PipelineData,
37 ) -> Result<PipelineData, ShellError> {
38 length_row(call, input)
39 }
40
41 fn examples(&self) -> Vec<Example<'_>> {
42 vec![
43 Example {
44 description: "Count the number of items in a list",
45 example: "[1 2 3 4 5] | length",
46 result: Some(Value::test_int(5)),
47 },
48 Example {
49 description: "Count the number of rows in a table",
50 example: "[{a:1 b:2}, {a:2 b:3}] | length",
51 result: Some(Value::test_int(2)),
52 },
53 Example {
54 description: "Count the number of bytes in binary data",
55 example: "0x[01 02] | length",
56 result: Some(Value::test_int(2)),
57 },
58 Example {
59 description: "Count the length a null value",
60 example: "null | length",
61 result: Some(Value::test_int(0)),
62 },
63 ]
64 }
65}
66
67fn length_row(call: &Call, input: PipelineData) -> Result<PipelineData, ShellError> {
68 let span = input.span().unwrap_or(call.head);
69 match input {
70 PipelineData::Empty | PipelineData::Value(Value::Nothing { .. }, ..) => {
71 Ok(Value::int(0, call.head).into_pipeline_data())
72 }
73 PipelineData::Value(Value::Binary { val, .. }, ..) => {
74 Ok(Value::int(val.len() as i64, call.head).into_pipeline_data())
75 }
76 PipelineData::Value(Value::List { vals, .. }, ..) => {
77 Ok(Value::int(vals.len() as i64, call.head).into_pipeline_data())
78 }
79 PipelineData::ListStream(stream, ..) => {
80 Ok(Value::int(stream.into_iter().count() as i64, call.head).into_pipeline_data())
81 }
82 PipelineData::ByteStream(stream, ..) if stream.type_().is_binary_coercible() => {
83 Ok(Value::int(
84 match stream.reader() {
85 Some(r) => r.bytes().count() as i64,
86 None => 0,
87 },
88 call.head,
89 )
90 .into_pipeline_data())
91 }
92 _ => Err(ShellError::OnlySupportsThisInputType {
93 exp_input_type: "list, table, binary, and nothing".into(),
94 wrong_type: input.get_type().to_string(),
95 dst_span: call.head,
96 src_span: span,
97 }),
98 }
99}
100
101#[cfg(test)]
102mod test {
103 use super::*;
104
105 #[test]
106 fn test_examples() {
107 use crate::test_examples;
108
109 test_examples(Length {})
110 }
111}