nu_command/math/
log.rs

1use crate::math::utils::ensure_bounded;
2use nu_engine::command_prelude::*;
3use nu_protocol::Signals;
4
5#[derive(Clone)]
6pub struct MathLog;
7
8impl Command for MathLog {
9    fn name(&self) -> &str {
10        "math log"
11    }
12
13    fn signature(&self) -> Signature {
14        Signature::build("math log")
15            .required(
16                "base",
17                SyntaxShape::Number,
18                "Base for which the logarithm should be computed.",
19            )
20            .input_output_types(vec![
21                (Type::Number, Type::Float),
22                (
23                    Type::List(Box::new(Type::Number)),
24                    Type::List(Box::new(Type::Float)),
25                ),
26                (Type::Range, Type::List(Box::new(Type::Number))),
27            ])
28            .allow_variants_without_examples(true)
29            .category(Category::Math)
30    }
31
32    fn description(&self) -> &str {
33        "Returns the logarithm for an arbitrary base."
34    }
35
36    fn search_terms(&self) -> Vec<&str> {
37        vec!["base", "exponent", "inverse", "euler"]
38    }
39
40    fn is_const(&self) -> bool {
41        true
42    }
43
44    fn run(
45        &self,
46        engine_state: &EngineState,
47        stack: &mut Stack,
48        call: &Call,
49        input: PipelineData,
50    ) -> Result<PipelineData, ShellError> {
51        let head = call.head;
52        let base: Spanned<f64> = call.req(engine_state, stack, 0)?;
53        if let PipelineData::Value(ref v @ Value::Range { ref val, .. }, ..) = input {
54            let span = v.span();
55            ensure_bounded(val, span, head)?;
56        }
57        log(base, call.head, input, engine_state.signals())
58    }
59
60    fn run_const(
61        &self,
62        working_set: &StateWorkingSet,
63        call: &Call,
64        input: PipelineData,
65    ) -> Result<PipelineData, ShellError> {
66        let head = call.head;
67        let base: Spanned<f64> = call.req_const(working_set, 0)?;
68        if let PipelineData::Value(ref v @ Value::Range { ref val, .. }, ..) = input {
69            let span = v.span();
70            ensure_bounded(val, span, head)?;
71        }
72        log(base, call.head, input, working_set.permanent().signals())
73    }
74
75    fn examples(&self) -> Vec<Example<'_>> {
76        vec![
77            Example {
78                description: "Get the logarithm of 100 to the base 10",
79                example: "100 | math log 10",
80                result: Some(Value::test_float(2.0f64)),
81            },
82            Example {
83                example: "[16 8 4] | math log 2",
84                description: "Get the log2 of a list of values",
85                result: Some(Value::list(
86                    vec![
87                        Value::test_float(4.0),
88                        Value::test_float(3.0),
89                        Value::test_float(2.0),
90                    ],
91                    Span::test_data(),
92                )),
93            },
94        ]
95    }
96}
97
98fn log(
99    base: Spanned<f64>,
100    head: Span,
101    input: PipelineData,
102    signals: &Signals,
103) -> Result<PipelineData, ShellError> {
104    if base.item <= 0.0f64 {
105        return Err(ShellError::UnsupportedInput {
106            msg: "Base has to be greater 0".into(),
107            input: "value originates from here".into(),
108            msg_span: head,
109            input_span: base.span,
110        });
111    }
112    // This doesn't match explicit nulls
113    if let PipelineData::Empty = input {
114        return Err(ShellError::PipelineEmpty { dst_span: head });
115    }
116    let base = base.item;
117    input.map(move |value| operate(value, head, base), signals)
118}
119
120fn operate(value: Value, head: Span, base: f64) -> Value {
121    let span = value.span();
122    match value {
123        numeric @ (Value::Int { .. } | Value::Float { .. }) => {
124            let (val, span) = match numeric {
125                Value::Int { val, .. } => (val as f64, span),
126                Value::Float { val, .. } => (val, span),
127                _ => unreachable!(),
128            };
129
130            if val <= 0.0 {
131                return Value::error(
132                    ShellError::UnsupportedInput {
133                        msg: "'math log' undefined for values outside the open interval (0, Inf)."
134                            .into(),
135                        input: "value originates from here".into(),
136                        msg_span: head,
137                        input_span: span,
138                    },
139                    span,
140                );
141            }
142            // Specialize for better precision/performance
143            let val = if base == 10.0 {
144                val.log10()
145            } else if base == 2.0 {
146                val.log2()
147            } else {
148                val.log(base)
149            };
150
151            Value::float(val, span)
152        }
153        Value::Error { .. } => value,
154        other => Value::error(
155            ShellError::OnlySupportsThisInputType {
156                exp_input_type: "numeric".into(),
157                wrong_type: other.get_type().to_string(),
158                dst_span: head,
159                src_span: other.span(),
160            },
161            head,
162        ),
163    }
164}
165
166#[cfg(test)]
167mod test {
168    use super::*;
169
170    #[test]
171    fn test_examples() {
172        use crate::test_examples;
173
174        test_examples(MathLog {})
175    }
176}