vrl/stdlib/
float.rs

1use crate::compiler::prelude::*;
2
3fn float(value: Value) -> Resolved {
4    match value {
5        v @ Value::Float(_) => Ok(v),
6        v => Err(format!("expected float, got {}", v.kind()).into()),
7    }
8}
9
10#[derive(Clone, Copy, Debug)]
11pub struct Float;
12
13impl Function for Float {
14    fn identifier(&self) -> &'static str {
15        "float"
16    }
17
18    fn usage(&self) -> &'static str {
19        "Returns `value` if it is a float, otherwise returns an error. This enables the type checker to guarantee that the returned value is a float and can be used in any function that expects a float."
20    }
21
22    fn category(&self) -> &'static str {
23        Category::Type.as_ref()
24    }
25
26    fn internal_failure_reasons(&self) -> &'static [&'static str] {
27        &["`value` is not a float."]
28    }
29
30    fn return_kind(&self) -> u16 {
31        kind::FLOAT
32    }
33
34    fn return_rules(&self) -> &'static [&'static str] {
35        &[
36            "Returns the `value` if it's a float.",
37            "Raises an error if not a float.",
38        ]
39    }
40
41    fn parameters(&self) -> &'static [Parameter] {
42        const PARAMETERS: &[Parameter] = &[Parameter::required(
43            "value",
44            kind::ANY,
45            "The value to check if it is a float.",
46        )];
47        PARAMETERS
48    }
49
50    fn examples(&self) -> &'static [Example] {
51        &[
52            example! {
53                title: "Declare a float type",
54                source: indoc! {r#"
55                    . = { "value": 42.0 }
56                    float(.value)
57                "#},
58                result: Ok("42.0"),
59            },
60            example! {
61                title: "Declare a float type (literal)",
62                source: "float(3.1415)",
63                result: Ok("3.1415"),
64            },
65            example! {
66                title: "Invalid float type",
67                source: "float!(true)",
68                result: Err(
69                    r#"function call error for "float" at (0:12): expected float, got boolean"#,
70                ),
71            },
72        ]
73    }
74
75    fn compile(
76        &self,
77        _state: &state::TypeState,
78        _ctx: &mut FunctionCompileContext,
79        arguments: ArgumentList,
80    ) -> Compiled {
81        let value = arguments.required("value");
82
83        Ok(FloatFn { value }.as_expr())
84    }
85}
86
87#[derive(Debug, Clone)]
88struct FloatFn {
89    value: Box<dyn Expression>,
90}
91
92impl FunctionExpression for FloatFn {
93    fn resolve(&self, ctx: &mut Context) -> Resolved {
94        float(self.value.resolve(ctx)?)
95    }
96
97    fn type_def(&self, state: &state::TypeState) -> TypeDef {
98        let non_float = !self.value.type_def(state).is_float();
99
100        TypeDef::float().maybe_fallible(non_float)
101    }
102}