rdf_fusion_functions/scalar/numeric/
mul.rs

1use crate::scalar::dispatch::dispatch_binary_typed_value;
2use crate::scalar::sparql_op_impl::{
3    ScalarSparqlOpImpl, create_typed_value_sparql_op_impl,
4};
5use crate::scalar::{ScalarSparqlOp, ScalarSparqlOpSignature, SparqlOpArity};
6use rdf_fusion_encoding::typed_value::TypedValueEncoding;
7use rdf_fusion_extensions::functions::BuiltinName;
8use rdf_fusion_extensions::functions::FunctionName;
9use rdf_fusion_model::{Numeric, NumericPair, ThinError, TypedValueRef};
10
11/// Implementation of the SPARQL `*` operator.
12#[derive(Debug, Hash, PartialEq, Eq)]
13pub struct MulSparqlOp;
14
15impl Default for MulSparqlOp {
16    fn default() -> Self {
17        Self::new()
18    }
19}
20
21impl MulSparqlOp {
22    const NAME: FunctionName = FunctionName::Builtin(BuiltinName::Mul);
23
24    /// Creates a new [MulSparqlOp].
25    pub fn new() -> Self {
26        Self {}
27    }
28}
29
30impl ScalarSparqlOp for MulSparqlOp {
31    fn name(&self) -> &FunctionName {
32        &Self::NAME
33    }
34
35    fn signature(&self) -> ScalarSparqlOpSignature {
36        ScalarSparqlOpSignature::default_with_arity(SparqlOpArity::Fixed(2))
37    }
38    fn typed_value_encoding_op(
39        &self,
40    ) -> Option<Box<dyn ScalarSparqlOpImpl<TypedValueEncoding>>> {
41        Some(create_typed_value_sparql_op_impl(|args| {
42            dispatch_binary_typed_value(
43                &args.args[0],
44                &args.args[1],
45                |lhs_value, rhs_value| {
46                    if let (
47                        TypedValueRef::NumericLiteral(lhs_numeric),
48                        TypedValueRef::NumericLiteral(rhs_numeric),
49                    ) = (lhs_value, rhs_value)
50                    {
51                        match NumericPair::with_casts_from(lhs_numeric, rhs_numeric) {
52                            NumericPair::Int(lhs, rhs) => {
53                                lhs.checked_mul(rhs).map(Numeric::Int)
54                            }
55                            NumericPair::Integer(lhs, rhs) => {
56                                lhs.checked_mul(rhs).map(Numeric::Integer)
57                            }
58                            NumericPair::Float(lhs, rhs) => Ok(Numeric::Float(lhs * rhs)),
59                            NumericPair::Double(lhs, rhs) => {
60                                Ok(Numeric::Double(lhs * rhs))
61                            }
62                            NumericPair::Decimal(lhs, rhs) => {
63                                lhs.checked_mul(rhs).map(Numeric::Decimal)
64                            }
65                        }
66                        .map(TypedValueRef::NumericLiteral)
67                    } else {
68                        ThinError::expected()
69                    }
70                },
71                |_, _| ThinError::expected(),
72            )
73        }))
74    }
75}