Skip to main content

graphrecords_query/capabilities/numeric/
logarithm.rs

1use crate::{
2    Failure, IndexValue, QueryResult, Scalar, ValueDomain,
3    error::numeric::{NonNumericValue, NonPositiveLogarithm},
4};
5use graphrecords_core::graphrecord::GraphRecordValue;
6
7pub trait ValueLogarithm: ValueDomain {
8    fn logarithm<'a>(label: &'static str, value: Self::Value<'a>) -> QueryResult<Self::Value<'a>>;
9}
10
11impl ValueLogarithm for Scalar {
12    fn logarithm<'a>(label: &'static str, value: Self::Value<'a>) -> QueryResult<Self::Value<'a>> {
13        match value {
14            GraphRecordValue::Int(integer) if integer <= 0 => {
15                Err(Failure::new(label, NonPositiveLogarithm::new(value)))
16            }
17            GraphRecordValue::Float(float) if float <= 0.0 => {
18                Err(Failure::new(label, NonPositiveLogarithm::new(value)))
19            }
20            GraphRecordValue::Int(integer) => Ok(GraphRecordValue::Float((integer as f64).ln())),
21            GraphRecordValue::Float(float) => Ok(GraphRecordValue::Float(float.ln())),
22            value => Err(Failure::new(label, NonNumericValue::new(value))),
23        }
24    }
25}
26
27impl ValueLogarithm for IndexValue<GraphRecordValue> {
28    fn logarithm<'a>(label: &'static str, value: Self::Value<'a>) -> QueryResult<Self::Value<'a>> {
29        match value {
30            GraphRecordValue::Int(integer) if integer <= 0 => {
31                Err(Failure::new(label, NonPositiveLogarithm::new(value)))
32            }
33            GraphRecordValue::Float(float) if float <= 0.0 => {
34                Err(Failure::new(label, NonPositiveLogarithm::new(value)))
35            }
36            GraphRecordValue::Int(integer) => Ok(GraphRecordValue::Float((integer as f64).ln())),
37            GraphRecordValue::Float(float) => Ok(GraphRecordValue::Float(float.ln())),
38            value => Err(Failure::new(label, NonNumericValue::new(value))),
39        }
40    }
41}