Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support additional functions #110

Merged
merged 3 commits into from
Oct 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ serde_json = "1.0.117"
rand = "0.8.5"
regex = "1.11.1"
num-format = "0.4.4"
uuid = { version = "1.8.0", features = ["fast-rng", "v4", "v7"] }

[dev-dependencies]
test-case = "3.3.1"
Expand Down
32 changes: 32 additions & 0 deletions src/evaluator/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ use rand::Rng;
use regex::Regex;
use std::borrow::{Borrow, Cow};
use std::collections::HashSet;
use std::time::{SystemTime, UNIX_EPOCH};
use uuid::Uuid;

use crate::datetime::{format_custom_date, parse_custom_format, parse_timezone_offset};
use crate::parser::expressions::check_balanced_brackets;
Expand Down Expand Up @@ -1060,6 +1062,36 @@ pub fn from_millis<'a>(
))
}

pub fn fn_millis<'a>(
context: FunctionContext<'a, '_>,
args: &[&'a Value<'a>],
) -> Result<&'a Value<'a>> {
max_args!(context, args, 0);

let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Time went backwards");

// Turning the timestamp to a string given that the stable millis function
// returns a u128 and the `Value::number` only supports f64.
Ok(Value::string(
context.arena,
timestamp.as_millis().to_string().as_str(),
))
}

pub fn fn_uuid<'a>(
context: FunctionContext<'a, '_>,
args: &[&'a Value<'a>],
) -> Result<&'a Value<'a>> {
max_args!(context, args, 0);

Ok(Value::string(
context.arena,
Uuid::new_v4().to_string().as_str(),
))
}

pub fn to_millis<'a>(
context: FunctionContext<'a, '_>,
args: &[&'a Value<'a>],
Expand Down
4 changes: 3 additions & 1 deletion src/evaluator/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ pub const UNDEFINED: Value = Value::Undefined;
pub const TRUE: Value = Value::Bool(true);
pub const FALSE: Value = Value::Bool(false);

/// The core value type for input, output and evaluation. There's a lot of lifetimes here to avoid
/// The core value type for input, output and evaluation.
///
/// There's a lot of lifetimes here to avoid
/// cloning any part of the input that should be kept in the output, avoiding heap allocations for
/// every Value, and allowing structural sharing.
///
Expand Down
14 changes: 8 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ impl<'a> JsonAta<'a> {
}

fn json_value_to_value(&self, json_value: &serde_json::Value) -> &'a mut Value<'a> {
return match json_value {
match json_value {
serde_json::Value::Null => Value::null(self.arena),
serde_json::Value::Bool(b) => self.arena.alloc(Value::Bool(*b)),
serde_json::Value::Number(n) => Value::number(self.arena, n.as_f64().unwrap()),
Expand All @@ -65,16 +65,16 @@ impl<'a> JsonAta<'a> {
array.push(self.json_value_to_value(v))
}

return array;
array
}
serde_json::Value::Object(o) => {
let object = Value::object_with_capacity(self.arena, o.len());
for (k, v) in o.iter() {
object.insert(k, self.json_value_to_value(v));
}
return object;
object
}
};
}
}

pub fn evaluate(
Expand Down Expand Up @@ -171,6 +171,8 @@ impl<'a> JsonAta<'a> {
bind_native!("trim", 1, fn_trim);
bind_native!("uppercase", 1, fn_uppercase);
bind_native!("zip", 1, fn_zip);
bind_native!("millis", 0, fn_millis);
bind_native!("uuid", 0, fn_uuid);

let chain_ast = Some(parser::parse(
"function($f, $g) { function($x){ $g($f($x)) } }",
Expand Down Expand Up @@ -217,7 +219,7 @@ mod tests {
let jsonata = JsonAta::new("$map([1,4,9,16], $squareroot)", &arena).unwrap();
jsonata.register_function("squareroot", 1, |ctx, args| {
let num = &args[0];
return Ok(Value::number(ctx.arena, (num.as_f64()).sqrt()));
Ok(Value::number(ctx.arena, (num.as_f64()).sqrt()))
});

let result = jsonata.evaluate(Some(r#"anything"#), None);
Expand All @@ -238,7 +240,7 @@ mod tests {
let jsonata = JsonAta::new("$filter([1,4,9,16], $even)", &arena).unwrap();
jsonata.register_function("even", 1, |_ctx, args| {
let num = &args[0];
return Ok(Value::bool((num.as_f64()) % 2.0 == 0.0));
Ok(Value::bool((num.as_f64()) % 2.0 == 0.0))
});

let result = jsonata.evaluate(Some(r#"anything"#), None);
Expand Down
14 changes: 13 additions & 1 deletion tests/testsuite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ extern crate test_generator;

use bumpalo::Bump;
use jsonata_rs::{ArrayFlags, JsonAta, Value};
use regex::Regex;
use std::fs;
use std::path;

Expand Down Expand Up @@ -104,12 +105,23 @@ fn test_case(resource: &str) {
}
assert!(found);
}
} else if case["result_re"].is_string() {
// Ability to define a regular expression to match the result. This strategy is useful
// to validate the result of an expression that's not deterministic (like the $millis() function).
let regex_pattern = Regex::new(case["result_re"].as_str().as_ref())
.expect("Should have a valid regex expression");

assert!(
regex_pattern.is_match(&result.as_str()),
"Value: {result:?}, did not match expected result_re",
);
} else {
eprintln!("RESULT: {}", result);
assert_eq!(result, expected_result);
}
}
Err(error) => {
eprintln!("{}", error);
eprintln!("ERROR: {}", error);
let code = if !case["error"].is_undefined() {
&case["error"]["code"]
} else {
Expand Down
6 changes: 6 additions & 0 deletions tests/testsuite/groups/function-millis/case000.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"expr": "$millis()",
"dataset": null,
"bindings": {},
"result_re": "(\\d+)"
}
6 changes: 6 additions & 0 deletions tests/testsuite/groups/function-millis/case001.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"expr": "$millis() & \"-SUFFIX\"",
"dataset": null,
"bindings": {},
"result_re": "(\\d+)-SUFFIX"
}
6 changes: 6 additions & 0 deletions tests/testsuite/groups/function-uuid/case000.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"expr": "$uuid()",
"dataset": null,
"bindings": {},
"result_re": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"
}
Loading