Enum NumberValue

Source
pub enum NumberValue {
    Integer(i64),
    Float(f64),
}
Expand description

Specialized representation for numeric values to optimize memory usage.

This enum provides different representations for integers and floating-point values, allowing for more efficient memory usage and operations.

Variants§

§

Integer(i64)

Integer value

§

Float(f64)

Floating point value

Implementations§

Source§

impl NumberValue

Source

pub fn from_i64(value: i64) -> Self

Creates a new NumberValue from an i64.

Examples found in repository?
examples/custom_advance.rs (line 19)
12    fn evaluate<'a>(
13        &self,
14        args: &'a [DataValue<'a>],
15        arena: &'a DataArena,
16    ) -> Result<&'a DataValue<'a>> {
17        // Default to 1 if no arguments provided
18        if args.is_empty() {
19            return Ok(arena.alloc(DataValue::Number(NumberValue::from_i64(1))));
20        }
21
22        // Calculate product of all numeric values
23        let mut product = 1.0;
24        for arg in args {
25            if let Some(n) = arg.as_f64() {
26                product *= n;
27            }
28        }
29
30        // Return the result
31        Ok(arena.alloc(DataValue::Number(NumberValue::from_f64(product))))
32    }
33}
34
35// Define a custom operator that returns the median of a set of numbers
36#[derive(Debug)]
37struct Median;
38
39impl CustomOperator for Median {
40    fn evaluate<'a>(
41        &self,
42        args: &'a [DataValue<'a>],
43        arena: &'a DataArena,
44    ) -> Result<&'a DataValue<'a>> {
45        // Collect all numeric values
46        let mut numbers = Vec::new();
47
48        // Handle the case where a single array is passed
49        if args.len() == 1 && args[0].is_array() {
50            if let Some(items) = args[0].as_array() {
51                for item in items {
52                    if let Some(n) = item.as_f64() {
53                        numbers.push(n);
54                    }
55                }
56            }
57        } else {
58            // Handle the case where multiple arguments are passed
59            for arg in args {
60                if let Some(n) = arg.as_f64() {
61                    numbers.push(n);
62                }
63            }
64        }
65
66        // Return 0 for empty arrays
67        if numbers.is_empty() {
68            return Ok(arena.alloc(DataValue::Number(NumberValue::from_i64(0))));
69        }
70
71        // Sort the numbers
72        numbers.sort_by(|a, b| a.partial_cmp(b).unwrap());
73
74        // Calculate the median
75        let median = if numbers.len() % 2 == 0 {
76            // Even number of elements - average the middle two
77            let mid = numbers.len() / 2;
78            (numbers[mid - 1] + numbers[mid]) / 2.0
79        } else {
80            // Odd number of elements - take the middle one
81            numbers[numbers.len() / 2]
82        };
83
84        // Return the result
85        Ok(arena.alloc(DataValue::Number(NumberValue::from_f64(median))))
86    }
Source

pub fn from_f64(value: f64) -> Self

Creates a new NumberValue from an f64.

Examples found in repository?
examples/custom_simple.rs (line 14)
8fn double(args: Vec<DataValue>) -> std::result::Result<DataValue, String> {
9    if args.is_empty() {
10        return Err("double operator requires at least one argument".to_string());
11    }
12
13    if let Some(n) = args[0].as_f64() {
14        return Ok(DataValue::Number(NumberValue::from_f64(n * 2.0)));
15    }
16
17    Err("Argument must be a number".to_string())
18}
More examples
Hide additional examples
examples/custom_advance.rs (line 31)
12    fn evaluate<'a>(
13        &self,
14        args: &'a [DataValue<'a>],
15        arena: &'a DataArena,
16    ) -> Result<&'a DataValue<'a>> {
17        // Default to 1 if no arguments provided
18        if args.is_empty() {
19            return Ok(arena.alloc(DataValue::Number(NumberValue::from_i64(1))));
20        }
21
22        // Calculate product of all numeric values
23        let mut product = 1.0;
24        for arg in args {
25            if let Some(n) = arg.as_f64() {
26                product *= n;
27            }
28        }
29
30        // Return the result
31        Ok(arena.alloc(DataValue::Number(NumberValue::from_f64(product))))
32    }
33}
34
35// Define a custom operator that returns the median of a set of numbers
36#[derive(Debug)]
37struct Median;
38
39impl CustomOperator for Median {
40    fn evaluate<'a>(
41        &self,
42        args: &'a [DataValue<'a>],
43        arena: &'a DataArena,
44    ) -> Result<&'a DataValue<'a>> {
45        // Collect all numeric values
46        let mut numbers = Vec::new();
47
48        // Handle the case where a single array is passed
49        if args.len() == 1 && args[0].is_array() {
50            if let Some(items) = args[0].as_array() {
51                for item in items {
52                    if let Some(n) = item.as_f64() {
53                        numbers.push(n);
54                    }
55                }
56            }
57        } else {
58            // Handle the case where multiple arguments are passed
59            for arg in args {
60                if let Some(n) = arg.as_f64() {
61                    numbers.push(n);
62                }
63            }
64        }
65
66        // Return 0 for empty arrays
67        if numbers.is_empty() {
68            return Ok(arena.alloc(DataValue::Number(NumberValue::from_i64(0))));
69        }
70
71        // Sort the numbers
72        numbers.sort_by(|a, b| a.partial_cmp(b).unwrap());
73
74        // Calculate the median
75        let median = if numbers.len() % 2 == 0 {
76            // Even number of elements - average the middle two
77            let mid = numbers.len() / 2;
78            (numbers[mid - 1] + numbers[mid]) / 2.0
79        } else {
80            // Odd number of elements - take the middle one
81            numbers[numbers.len() / 2]
82        };
83
84        // Return the result
85        Ok(arena.alloc(DataValue::Number(NumberValue::from_f64(median))))
86    }
Source

pub fn is_integer(&self) -> bool

Returns true if the value is an integer.

Source

pub fn is_float(&self) -> bool

Returns true if the value is a floating point.

Source

pub fn as_i64(&self) -> Option<i64>

Returns the value as an i64, if possible.

Source

pub fn as_f64(&self) -> f64

Returns the value as an f64.

Source

pub fn add(&self, other: &NumberValue) -> NumberValue

Adds another NumberValue to this one.

Source

pub fn subtract(&self, other: &NumberValue) -> NumberValue

Subtracts another NumberValue from this one.

Source

pub fn multiply(&self, other: &NumberValue) -> NumberValue

Multiplies this NumberValue by another.

Source

pub fn divide(&self, other: &NumberValue) -> Option<NumberValue>

Divides this NumberValue by another.

Source

pub fn modulo(&self, other: &NumberValue) -> Option<NumberValue>

Returns the modulo of this NumberValue by another.

Trait Implementations§

Source§

impl Clone for NumberValue

Source§

fn clone(&self) -> NumberValue

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for NumberValue

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for NumberValue

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for NumberValue

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for NumberValue

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Copy for NumberValue

Source§

impl Eq for NumberValue

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.