nushell/crates/nu-command/src/length.rs
2021-09-07 19:35:59 +12:00

53 lines
1.3 KiB
Rust

use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EvaluationContext};
use nu_protocol::{Signature, Value};
pub struct Length;
impl Command for Length {
fn name(&self) -> &str {
"length"
}
fn usage(&self) -> &str {
"Count the number of elements in the input."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("length")
}
fn run(
&self,
_context: &EvaluationContext,
call: &Call,
input: Value,
) -> Result<nu_protocol::Value, nu_protocol::ShellError> {
match input {
Value::List { vals: val, .. } => {
let length = val.len();
Ok(Value::Int {
val: length as i64,
span: call.head,
})
}
Value::Stream { stream, .. } => {
let length = stream.count();
Ok(Value::Int {
val: length as i64,
span: call.head,
})
}
Value::Nothing { .. } => Ok(Value::Int {
val: 0,
span: call.head,
}),
_ => Ok(Value::Int {
val: 1,
span: call.head,
}),
}
}
}