[libshumate] Add coalesce expression



commit 2a929026e4fed60351c42f83d3a536fdda511ffc
Author: James Westman <james jwestman net>
Date:   Thu Oct 13 17:00:57 2022 -0500

    Add coalesce expression
    
    The coalesce expression returns the first argument which does not fail
    to evaluated and evaluates to a non-null value.

 shumate/vector/shumate-vector-expression-filter.c | 20 ++++++++++++++++++++
 tests/vector-expression.c                         |  3 +++
 2 files changed, 23 insertions(+)
---
diff --git a/shumate/vector/shumate-vector-expression-filter.c 
b/shumate/vector/shumate-vector-expression-filter.c
index 7412316..1092381 100644
--- a/shumate/vector/shumate-vector-expression-filter.c
+++ b/shumate/vector/shumate-vector-expression-filter.c
@@ -41,6 +41,7 @@ typedef enum {
   EXPR_SUB,
   EXPR_MUL,
   EXPR_DIV,
+  EXPR_COALESCE,
 } ExpressionType;
 
 struct _ShumateVectorExpressionFilter
@@ -176,6 +177,8 @@ shumate_vector_expression_filter_from_json_array (JsonArray *array, GError **err
     }
   else if (g_strcmp0 ("case", op) == 0)
     self->type = EXPR_CASE;
+  else if (g_strcmp0 ("coalesce", op) == 0)
+    self->type = EXPR_COALESCE;
   else
     {
       g_set_error (error,
@@ -508,6 +511,23 @@ shumate_vector_expression_filter_eval (ShumateVectorExpression  *expr,
       /* no case matched and there was no fallback */
       return FALSE;
 
+    case EXPR_COALESCE:
+      for (int i = 0; i < n_expressions; i ++)
+        {
+          if (!shumate_vector_expression_eval (expressions[i], scope, &value))
+            continue;
+
+          if (shumate_vector_value_is_null (&value))
+            continue;
+
+          shumate_vector_value_copy (&value, out);
+          return TRUE;
+        }
+
+      /* no expression succeeded, return null */
+      shumate_vector_value_unset (out);
+      return TRUE;
+
     default:
       g_assert_not_reached ();
     }
diff --git a/tests/vector-expression.c b/tests/vector-expression.c
index f3b4daa..7bcfe88 100644
--- a/tests/vector-expression.c
+++ b/tests/vector-expression.c
@@ -177,6 +177,9 @@ test_vector_expression_basic_filter (void)
   g_assert_true (filter ("[\"==\", [\"-\", 1], -1]"));
   g_assert_true (filter ("[\"==\", [\"*\", 5, 6, 7], 210]"));
   g_assert_true (filter ("[\"==\", [\"/\", 10, 4], 2.5]"));
+
+  g_assert_true (filter ("[\"==\", [\"coalesce\", null, [\"*\", 0, \"b\"], 2, 3], 2]"));
+  g_assert_true (filter ("[\"==\", [\"coalesce\", null, [\"*\", 0, \"b\"]], null]"));
 }
 
 


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]