drasi_core/evaluation/functions/numeric/
random.rs

1// Copyright 2024 The Drasi Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use async_trait::async_trait;
16use drasi_query_ast::ast;
17use rand::prelude::*;
18
19use crate::evaluation::functions::ScalarFunction;
20use crate::evaluation::variable_value::float::Float;
21use crate::evaluation::variable_value::VariableValue;
22use crate::evaluation::{ExpressionEvaluationContext, FunctionError, FunctionEvaluationError};
23
24#[derive(Debug)]
25pub struct Rand {}
26
27#[async_trait]
28impl ScalarFunction for Rand {
29    async fn call(
30        &self,
31        _context: &ExpressionEvaluationContext,
32        expression: &ast::FunctionExpression,
33        args: Vec<VariableValue>,
34    ) -> Result<VariableValue, FunctionError> {
35        if !args.is_empty() {
36            return Err(FunctionError {
37                function_name: expression.name.to_string(),
38                error: FunctionEvaluationError::InvalidArgumentCount,
39            });
40        }
41        let mut rng = rand::thread_rng();
42        Ok(VariableValue::Float(match Float::from_f64(rng.gen()) {
43            Some(f) => f,
44            None => {
45                return Err(FunctionError {
46                    function_name: expression.name.to_string(),
47                    error: FunctionEvaluationError::OverflowError,
48                })
49            }
50        }))
51    }
52}